[LeetCode] 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.

 找出两个字符串中不同的字母,且这个不同的字母只出现了一次,其他的字母出现了2次。利用XOR即可求解。

class Solution {
public:
    char findTheDifference(string s, string t) {
        char res = 0;
        for (char c : s)
            res ^= c;
        for (char c : t)
            res ^= c;
        return res;
    }
};
// 3 ms

因为题目中是2个字符串,故可以分别对两个字符串中的字母求和,再用这两个总和相减,得到的差即是所求的那个字母。

class Solution {
public:
    char findTheDifference(string s, string t) {
        int sum_s = 0, sum_t = 0;
        for (auto c : s)
            sum_s += c;
        for (auto c : t)
            sum_t += c;
        return sum_t - sum_s;
    }
};
// 3 ms

利用map存储s中字母出现的次数。形成一个查找表。使用t中字母查找,找不到的就是所求的那个字母。

class Solution {
public:
    char findTheDifference(string s, string t) {
        unordered_map<char, int> m;
        for (int i = 0; i != s.size(); i++) 
            m[s[i]]++;
        for (int i = 0; i != t.size(); i++) {
            if (m[t[i]] > 0)
                m[t[i]]--;
            else
                return t[i];
        }
    }
};
// 9 ms

相关参考:

[LeetCode] Single Number

 

posted @ 2017-07-12 10:33  immjc  阅读(145)  评论(0编辑  收藏  举报