LeetCode

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.

使用哈希表来记录每个字母出现的次数, 多出现的字符就是增加的字符.

class Solution {
public:
    char findTheDifference(string s, string t) {
        vector<int> nums(26, 0);
        for(int i = 0; i < s.length(); i++){
            nums[s[i] - 'a']++;
        }
        for(int i = 0; i < t.length(); i++){
            if(--nums[t[i] - 'a'] < 0) return t[i];
        }
        return 0;
    }
};

还可以使用异或. 由于s与t除了一个元素以外其他都相同, 所以使用0分别于s与t的每个元素异或, 得到的就是多余的那一个字符.

class Solution {
public:
    char findTheDifference(string s, string t) {
        char ch = 0;
        for(int i = 0; i < s.length(); i++){
            ch ^= s[i];
        }
        for(int i = 0; i < t.length(); i++){
            ch ^= t[i];
        }
        return ch;
    }
};

    输入关键词开始搜索