C++ solution using two map


  • 0
    J
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<string, char> mp;
            unordered_map<char, string> mp2;
            stringstream io(str);
            string wd;
            int i=0;
            while(getline(io,wd,' ')){
    
                if (mp.find(wd)!=mp.end()){
                    if (mp[wd]!=pattern[i])return false;//word find in mp and mp[wd] not equal to this position's  pattern[i]
                }else{
                    if (mp2.find(pattern[i])!=mp2.end()) return false;//same position patern[i] of the word find in mp2
                
                    //new word
                    mp[wd]=pattern[i];
                    mp2[pattern[i]]=wd;                
                }
                i++;
            }
            return i==pattern.size();
        }
    };

Log in to reply
 

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