LC 290. Word Pattern

Nilanjan Deb · April 6, 2020

This is my CPP solution.

class Solution {
private:
    vector<string> splitStr(string s){
        int n = s.size(),i = 0;
        vector<string> res;
        string store;
        while(i<n){
            if(s[i] == ' '){
                res.push_back(store);
                store.clear();
            }
            else{
                store.push_back(s[i]);
            }
            i++;
        }
        res.push_back(store);
        return res;
    }
public:
    bool wordPattern(string pattern, string str) {
        vector<string> exp = splitStr(str);
        vector<int> pattern_map(26,0);
        unordered_map<string,char> exp_map;
        int n = pattern.size(), m = exp.size();
        if(n!=m)
            return false;
        for(int i=0;i<n;i++){
            if((exp_map.find(exp[i])!=exp_map.end() && exp_map[exp[i]] != pattern[i]) ||(exp_map.find(exp[i])==exp_map.end() && pattern_map[pattern[i]-'a']))
                return false;
            else if(exp_map.find(exp[i])==exp_map.end() && !pattern_map[pattern[i]-'a']){
                exp_map[exp[i]] = pattern[i];
                pattern_map[pattern[i] - 'a'] = i+1;
            }
        }
        return true;
    }
};


Dicussion Forum