Jack Li's Blog

0290.Word Pattern

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char, string> mapP2S;
        unordered_map<string, char> mapS2P;
        
        int i = 0;
        int l = 0, r = 0;
        int n = s.size();
        
        while(l < n && r < n){
            // Split the string by space
            while(s[r] != ' ' && r < n) r++;    // ensure r range
            string sub = s.substr(l, r - l);    // blank index to left index

            // if pattern and string are all not recorded before, record it
            if(mapP2S.find(pattern[i]) == mapP2S.end() && mapS2P.find(sub) == mapS2P.end()){
                mapP2S[pattern[i]] = sub;
                mapS2P[sub] = pattern[i];
            } else {
                // if pattern or string are not mapping correctly, return false
                if(mapP2S[pattern[i]] != sub || mapS2P[sub] != pattern[i]){
                    return false;
                }
            }
            i++;    // pattern index increment
            while(s[r] == ' ' && r < n) r++; // move to next vocabulary
            l = r;  // left index moves to right
        }
        // Check if pattern uses completely
        if(i != pattern.size()) return false;
        return true;
    }
};