389_Find_the_Difference

Find the Difference

Difficulty Easy

tags bit mask

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.

思路:

又一次遇到的异或的小技巧, 经过连续异或之后,出现偶数次的被隐去, 出现奇数次的被保留。

solution 1

class Solution {
public:
    char findTheDifference(string s, string t) {
        char r = 0;
        for (char c:s) r ^= c;
        for (char c:t) r ^= c;
        return r;
    }
};
posted @ 2017-07-17 21:53  whensean  阅读(94)  评论(0)    收藏  举报