给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = “abcd”
t = “abcde”
输出:
e
解释:
‘e’ 是那个被添加的字母。
[java]
1.
public static char findTheDifference(String s, String t) {
char[] str_s = s.toCharArray();
char[] str_t = t.toCharArray();
Arrays.sort(str_s);
Arrays.sort(str_t);
int i = 0;
for(i = 0; i < str_s.length; i++) {
if(str_t[i] != str_s[i])
return str_t[i];
}
return str_t[i];
}
####2.空间复杂度和时间复杂度比起上面的都降低了
//空间复杂度和时间复杂度都降低了
public char findTheDifference(String s, String t) {
int a[]=new int[26];
for(int i=0;i<s.length();i++)
a[s.charAt(i)-'a']++;
for(int j=0;j<t.length();j++)
a[t.charAt(j)-'a']--;
for(int k=0;k<a.length;k++){
if(a[k]!=0)
return (char)(k+'a');
}
return 0;
}
3.利用位运算去解决
在一堆重复两次的数中找出一个单独只存在一个的数的问题一样,用异或操作消除所有重复的元素,剩余的元素即为所求
public char findTheDifference(String s, String t) {
char res = 0;
for(int i = 0; i < s.length(); i++)
res ^= s.charAt(i);
for(int i = 0; i < t.length(); i++)
res ^= t.charAt(i);
return res;
}
}
文末附上某不知名大佬的代码(膜拜.jpg):
public char findTheDifference(String s, String t) {
return (char) (s + t).chars().reduce(0, (c, d) -> c ^ d);
}