leetcode 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中的字符一一异或,可以得到唯一多出来的字符,但这样需要两个指针,所以比较复杂,由于异或具有交换性,所以可以将s中的字符异或之后再异或t中的字符,结果一样。

1
2
3
4
5
6
7
8
9
10
11
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;
}
};