题意:给出两个字符串s和t,均只含有小写字母,找出两字符串的不同,并输出字符
例子:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
解题思路:一想到比较不同,自然会想到异或运算,然而还需注意到一点:在java中,byte、char、short进行运算时,他们之间不会相互转化,首先会将自身先转换为int类型,如果要转换回本类型,则必须在结果前加上强制转换符
代码如下:
public class Solution {
public char findTheDifference(String s, String t) {
char temp = 0;
for(int i = 0; i < s.length(); i++) {
temp = (char) (temp ^ s.charAt(i));
}
for(int j = 0; j < t.length(); j++) {
temp = (char) (temp ^ t.charAt(j));
}
return temp;
}
}