【简单】389. 找不同

【题目】
给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请找出在 t 中被添加的字母。
来源:leetcode
链接:https://leetcode-cn.com/problems/find-the-difference/
【示例】
【方法一:太机智了】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :6.8 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    char findTheDifference(string s, string t) {
        int sum = 0;
        for (auto i : t)
            sum += i;
        for (auto i : s)
            sum -= i;
        return sum;
    }
};

【方法二】

class Solution {
public:
    int hashchar[26]={0};
    char findTheDifference(string s, string t) {
        s+=t;
        for(auto c:s)
            hashchar[c-'a']++;
        for(int i=0;i<26;i++)
            if(hashchar[i]%2)
                return 'a'+i;
        return 'a';
    }
};

【方法三:常规】

class Solution {
public:
    char findTheDifference(string s, string t) {
        int len=s.size();
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        for(int i=0;i<len;i++)
            if(s[i]!=t[i])
                return t[i];
        return t[len];
    }
};

你可能感兴趣的:(刷题,#,leetcode)