C++ One Hash Table Solution 0ms


  • 2
    Y
    bool wordPattern(string pattern, string str) {
        int *a = new int[26]();
        unordered_map<string, int> m;
    
        int patternIdx = 0, startIndex = 0;
    
        if (str.length() && str[str.length() - 1] != ' ') {
            str += ' ';
        }
    
        for (int i = 0; i < str.length(); ++i) {
            if (patternIdx == pattern.length()) {
                return false;
            }
    
            if (str[i] == ' ') {
                string sub = str.substr(startIndex, i - startIndex);
                startIndex = ++i;
    
                int aIdx = pattern[patternIdx] - 97;
                if (m.find(sub) == m.end()) {
                    if (!a[aIdx]) {
                        m[sub] = pattern[patternIdx];
                        a[aIdx] = 1;
                    } else {
                        return false;
                    }
                } else if (m[sub] != pattern[patternIdx]){
                    return false;
                }
                patternIdx++;
            }
        }
        return patternIdx == pattern.length();
    }

Log in to reply
 

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