C++ simple solution with explanation


  • 0
    S

    Here we will use a helper array of 26 numbers.
    now we count all the chars and put it into its own cell
    example "aaabccddddde" will be something like
    3 1 2 5 1 ... that corresponds to
    a b c d e ...

    then, having the count of chars, we simply go over string t and deduct now similar way.
    if the second string is "aaabcddddde" (missing one c) you will have leftovers as
    0 0 1 0 0 ... that corresponds to
    a b c d e ...

    Now we simply find that +1 or -1 - that will be our char

    char findTheDifference(string s, string t)
        {
            vector<int> chMap(26, 0);
            
            // count every char for string s
            for (int i=0; i<s.size(); ++i)
            {
                chMap[s[i]-'a'] += 1;
            }
            
            // now substitute every char from t
            for (int i=0; i<t.size(); ++i)
            {
                chMap[t[i]-'a'] -=1;
            }
            
            // now we should have whether +1/-1 and all the rest 0
            for (int i=0; i<26; ++i)
            {
                if (chMap[i] != 0)
                    return 'a' + i;
            }
            
            return 0;
        }
    

Log in to reply
 

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