C++ Hashmap Solution

  • 0
    class Solution {
        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

    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

    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

    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


    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.