389. Find the Difference 找不同

2017-07-30  本文已影响0人  这就是一个随意的名字

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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读