C++ Hashmap Solution


  • 0
    class Solution {
    public:
        char findTheDifference(string s, string t) {
            char diff = 0;
            int cnt[256] = {0};
            for (char c : s) cnt[c]++;
            for (char c : t) if (--cnt[c] < 0) return c;
            return diff;
        }
    };
    

  • 0
    G

    Could you please explain "for(char c:s) " for me? In fact I know what this code means and it can run correctly.However I can't find some explanation about this grammar in google or my textbook.


  • 0

    @gpf828
    Hi, gpf828. This is called range_based for loop. It was introduced since c++11.

    Check out this link :
    Range_based for loop.
    There are good examples in the article.


  • 0
    Y

    Wow. I didn't know that i can use character as a array index. i have a question. why you declare size of cnt 256?


  • 0

    @YuYeong

    Hi, YuYeong,
    Because the size of full Ascii Table is 256.
    Since there are only lowercase letters, cnt[128] will also work for this question.


Log in to reply
 

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