Share my easy to understand C++ with comment

  • 2
    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> c_to_str;
        unordered_set<string> used_strs;
        stringstream ss(str);
        string s;
        for(auto c : pattern)
            // if test string used up, return false
            if(!(ss >> s)) 
                return false;
            // if we meet a new char in pattern, record the char-word pair
            if (c_to_str.count(c) == 0)
                // if the word is used for other char before, return false
                if (!used_strs.insert(s).second)
                    return false;
                c_to_str.emplace(c, s);
            // otherwise, we check if the char matches to the same word as before
            else if (c_to_str[c] != s)
                return false;
        // if the test string is not used up, the match fails
        return !(ss >> s); 

Log in to reply

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