Easy to understand and use two maps!


  • 0
    C
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<string,char> ump1;
            unordered_map<char,string> ump2;
            vector<string> str2;
            int str_len = str.size();
            int i = 0;
            while ( i < str_len){
                string str_tmp = "";
                while (str[i] != ' ' && i < str_len){
                    str_tmp += str[i];
                    ++i;
                }
                str2.push_back(str_tmp);
                ++i;
            }
            if (pattern.size() != str2.size()) return false;
            
            for (int i = 0; i < pattern.size(); ++i){
                ump1[str2[i]] = pattern[i];
                // cout<< str2[i] <<endl;
                ump2[pattern[i]] = str2[i];
            }
            for (int i = 0; i < pattern.size(); ++i){
                if (ump1[str2[i]] != pattern[i] || ump2[pattern[i]] != str2[i]) return false;
            }
            return true;
        }
    };
    

Log in to reply
 

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