my simple c++ solution using unordered_map


  • 0
    F
    bool wordPattern(string pattern, string str) {
       unordered_map<char,string> cs;
       unordered_map<string,char> sc;
       str.append(1, ' ');
       string tmp;
       int idx = 0;
       
       for(int i = 0; i < str.size(); ++i) {
           char tc = str[i];
           if(tc == ' ') {
               char pat = pattern[idx++];
               auto it = cs.find(pat);
    
               auto hit = sc.find(tmp);
               if(hit != sc.end() && hit->second != pat) return false;
             
               if(it != cs.end()) {
                   if(it->second != tmp)  return false;
               } else {
                   cs[pat] = tmp;
                   sc[tmp] = pat;
               }
               tmp = "";
           } else {
               tmp.append(1, tc);
           }
       } 
       return pattern.size() == idx;
    }

Log in to reply
 

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