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.
我的解答:
利用异或的性质 A^A = 0, A ^ 0 = A
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> a(26, 0);
char rs;
for(int i = 0; i < s.length(); ++i){
a[s[i] - 'a']++;
}
for(int i = 0; i < t.length(); ++i){
a[t[i] - 'a']--;
}
for(int i = 0; i < a.size(); ++i){
if(a[i] != 0){
rs = 'a' + i;
}
}
return rs;
}
};
利用异或的性质 A^A = 0, A ^ 0 = A
class Solution { public: char findTheDifference(string s, string t) { char c; for(int i = 0; i < s.length(); ++i){ c ^= s[i]; }
return c;for(int i = 0; i < t.length(); ++i){ c ^= t[i]; }
}};