C++ 0ms two maps two pointers solution


  • 0
    bool wordPattern(string pattern, string str) {
            unordered_map<char,string>m;
            unordered_map<string,char>m2;
            string::iterator head=str.begin();
            string::iterator tail=str.begin();
            for(int i=0;i<pattern.size();i++){
                string word="";
                char c=pattern[i];
                while(*tail!=' ') {tail++;if(tail==str.end()) break;}
                word.assign(head,tail);
                if(m[c]==""&&!m2[word]) m[c]=word,m2[word]=c;
                else if(m[c]!=word||m2[word]!=c) return false;
                head=tail+1;
                tail++;
            }
            return tail==str.end()+1;
        }
    

Log in to reply
 

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