My C++ solution - 0ms


  • 0
    E
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            if(pattern.size() == 0 && str.size() == 0) {
                return true;
            }
            if(pattern.size() == 0 || str.size() == 0) {
                return false;
            }
            unordered_map<char, string> map1;
            unordered_map<string, char> map2;
            int index1 = 0;
            int index2 = 0;
            int start2 = 0;
            while(index1 < pattern.size() && index2 < str.size()) {
                while(str[index2] != ' ' && index2 < str.size()) {
                    ++index2;
                }
                string tmp = str.substr(start2, index2 - start2);
                if(map1.find(pattern[index1]) == map1.end() && map2.find(tmp) == map2.end()) {
                    map1[pattern[index1]] = tmp;
                    map2[tmp] = pattern[index1];
                    ++index1;
                    ++index2;
                    start2 = index2;
                }
                else if(map1[pattern[index1]] != tmp || map2[tmp] != pattern[index1]) {
                    return false;
                }
                else {
                    ++index1;
                    ++index2;
                    start2 = index2;
                }
            }
            return index1 == pattern.size() && index2 == str.size() + 1;
        }
    };

  • 0
    S

    why do you need two maps to keep track of them?


Log in to reply
 

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