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.

/*
 *这里需要注意的是加入的字符可能已经存在于字符串中,例如测试用
 *例 "abcd" "abcda"
 */
class Solution {
public:
    char findTheDifference(string s, string t) {
        int map[26] = {0};
        char res;
        for(auto c:s){
            int pos = c - 'a';
            map[pos]++;
        }

        for(auto m:t){
            int pos = m - 'a';
            if(map[pos] == 0){
                res = m;
                break;
            }
            map[pos]--;
        }

        return res;
    }
};
class Solution {
public:
    char findTheDifference(string s, string t) {
        short int res;

        for(auto c:s)
            res ^=  (int)c;

        for(auto m:t)
            res ^= (int)m;

        return (char)res;
    }
};

results matching ""

    No results matching ""