题目
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
代码模板:
class Solution {
public char findTheDifference(String s, String t) {
}
}
分析
两种解法:
- 分别算出ASCII码sum,再相减,得到的就是多余的那个char
- 异或,因为a^a=0,一直异或下去,最后就能得到多余的那个char
解答
方法一:sum之差
class Solution {
public char findTheDifference(String s, String t) {
int sumS = 0;
int sumT = 0;
for(int i =0;i < s.length();i++){
sumS += s.charAt(i);
}
for(int j = 0;j<t.length();j++){
sumT += t.charAt(j);
}
int result = sumT-sumS;
return (char)result;
}
}
方法二:异或
class Solution {
public char findTheDifference(String s, String t) {
int result=0;
for(int i =0;i < s.length();i++){
result ^= s.charAt(i);
}
for(int j = 0;j<t.length();j++){
result ^= t.charAt(j);
}
return (char)result;
}
}