[字符串]leetcode389:找不同(easy)

題目:
在這裏插入圖片描述
題解:

  • 題目比較簡單,直接看代碼及註解即可。

代碼如下:

class Solution {
public:
    //題解1:統計字符串s和t的26個字母的個數,然後遍歷26個字母,返回不同數量的字母
    char findTheDifference_1(string s, string t) {
        int count_s[26],count_t[26];
        memset(count_s,0,sizeof(count_s));
        memset(count_t,0,sizeof(count_t));
        for(char& c:s)count_s[c-'a']++;
        for(char& c:t)count_t[c-'a']++;
        for(int i=0;i<26;++i){
            if(count_s[i]!=count_t[i])
                return 'a'+i;
        }
        return 'a';
    }

    //題解2:異或,a^a=0,a^0=a
    char findTheDifference_2(string s,string t){
        int res=0,n=s.size();
        for(int i=0;i<n;++i){
            //注意assic碼整形提升爲相對應的10進制數了,所以最後結果要轉換爲assic碼
            res^=s[i];
            res^=t[i];
        }
        res^=t[n];
        return char(res);
    }

    //題解3:相減
    char findTheDifference_3(string s,string t){
        int res=0;
        //由於t比s多一位,所以s用減,t用加
        for(char c:s)res-=c;
        for(char c:t)res+=c;
        //最後結果要轉換爲對應的assic碼
        return char(res);
    }

    //題解4:對兩個字符串排序之後,相對應的位比較assic碼即可
    char findTheDifference(string s,string t){
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        for(int i=0;i<s.size();++i){
            if(s[i]!=t[i])return t[i];
        }
        return t.back();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章