C++_2 different methods_Sort(28ms)_Bit manipulation(4ms)


  • 0

    Sort:

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

    Bit manipulation (Similar with find out the different number in an array)

    class Solution {
    public:
    char findTheDifference(string s, string t) {
        if(s.size() < 1) return t[0];
        char res = s[0];
        for(int i = 1; i < s.size(); i++){
            res ^= s[i];
        }
        for(int i = 0; i < t.size(); i++){
            res ^= t[i];
        }
        
        return res;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.