LeetCode: 389 Find the Difference(easy) C++

题目:

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) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        auto r = mismatch(s.begin(), s.end(), t.begin());
        return (*r.second);
    }
};

别人的(1):

class Solution {
public:
    char findTheDifference(string s, string t) {
        // Similar to single number. Can do using hashmap...
        int charmap[26] = {0};
        for(char c: t) {
            charmap[c-'a']++;
        }
        // Iterate over s, one letter will have count 1 left
        for(char c: s) {
            charmap[c-'a']--;
        }
        for(int i=0;i<26;i++) {
            if (charmap[i] == 1)
                return 'a'+i;
        }
        return -1;
    }
};

别人的(2):

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

猜你喜欢

转载自blog.csdn.net/lxin_liu/article/details/85000529