LeetCode之Find the Difference
【摘要】 1、题目
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one mor...
1、题目
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
-
Input:
-
s = "abcd"
-
t = "abcde"
-
-
Output:
-
e
-
-
Explanation:
-
'e' is the letter that was added.
please:
Input:
s = "a"
t = "aa"
Output:
a
2、代码实现
-
public class Solution {
-
public static char findTheDifference(String s, String t) {
-
if (s == null || t.length() == 0)
-
return t.charAt(0);
-
if (t == null || t.length() == 0)
-
return s.charAt(0);
-
if (s == null && t == null)
-
return 0;
-
int[] a = new int[30];
-
char[] tChars = t.toCharArray();
-
char[] sChars = s.toCharArray();
-
int sLength = s.length();
-
int tLength = t.length();
-
if (sLength > tLength) {
-
for (int i = 0; i < sChars.length; i++) {
-
if (a[sChars[i] - 97] != 0)
-
a[sChars[i] - 97] = ++(a[sChars[i] - 97]);
-
else
-
a[sChars[i] - 97] = 2;
-
}
-
for (int i = 0; i < tChars.length; i++) {
-
a[tChars[i] - 97] = --(a[tChars[i] - 97]);
-
}
-
} else {
-
for (int i = 0; i < tChars.length; i++) {
-
if (a[tChars[i] - 97] != 0)
-
a[tChars[i] - 97] = ++(a[tChars[i] - 97]);
-
else
-
a[tChars[i] - 97] = 2;
-
}
-
for (int i = 0; i < sChars.length; i++) {
-
a[sChars[i] - 97] = --(a[sChars[i] - 97]);
-
}
-
}
-
for (int i = 0; i < 30; i ++) {
-
if (a[i] >= 2) {
-
return (char) (i + 97);
-
}
-
}
-
return 0;
-
}
-
}
3、总结
看到2个字符串对比,我么可以先转化为字符数组,下表从A - 65 活着 a - 95 开始,也就是从下表0开始,然后要注意2个字符串里面可能包含同样的元素有几个的情况,相同就往上加,另外一个就减,但是他们最多相差1个字符,所以,我们可可以肯定,比我们一开始设置的大,也就是3,然后如果没有重复的数据,那么一样的就为1,肯定有一个为2.
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/67845937
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)