389. Find the Difference 找不同

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.
给定只含小写字母的字符串s和t,其中t由s混排并在随机位置添加了一个字母而得到,请找出添加的那个字母。


思路
与在一堆重复两次的数中找出一个单独只存在一个的数的问题一样,用异或操作消除所有重复的元素,剩余的元素即为所求

class Solution {
public:
    char findTheDifference(string s, string t) {
        int tmp=0;
        for(char c:s){
            tmp ^=c;
        }
        for(char c:t){
            tmp ^=c;
        }
        return char(tmp);
    }
};
public class Solution {
    public char findTheDifference(String s, String t) {
        char[] cs=s.toCharArray();
        char[] ct=t.toCharArray();
        char tmp=0;
        for(char c:cs)
            tmp^=c;
        for(char c:ct)
            tmp^=c;
        return tmp;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容