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.
我的解答:

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];
        }
    
        for(int i = 0; i < t.length(); ++i){
            c ^= t[i];
        }
return c;
}};

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章