LeetCode——Find the Difference

LeetCode——Find the Difference

Question

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.

Solution

  1. 用hash table求解,时间复杂度为O(2n)

  2. 用异或求解,这道题和single number 的问题是一个意思,两个字符串中,找出那个单个的字符。时间复杂度为O(n)。

Answer

class Solution {
public:
    char findTheDifference(string s, string t) {
        map<char, int> dict;
        for (char c : s)
            dict[c]++;
        map<char, int> dict2;
        for (char c : t) {
            dict2[c]++;
            if (dict2[c] > dict[c])
                return c;
        }
    }
};

用异或求解。

class Solution {
public:
    char findTheDifference(string s, string t) {
        char r=0;
        for(char c:s) r ^=c;
        for(char c:t) r ^=c;
        return r;
    }
};
posted @ 2017-04-02 12:02  清水汪汪  阅读(180)  评论(0编辑  收藏  举报