-->

Sunday, January 15, 2017

290. Word Pattern

https://leetcode.com/problems/word-pattern/

Solution:
Use double hash maps to build up one-to-one relationship.

Code:
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<string> v(26, "");
        unordered_map<string, char> m;
        int i = 0, j = 0, l1 = pattern.size(), l2 = str.size();
        for(; i<l1 && j<l2; ++i){
            while(j<l2 && str[j] == ' ') ++j;
            int t = j;
            while(t<l2&&str[t] != ' ') ++t;
            string s = str.substr(j, t-j);
            if(v[pattern[i]-'a'] == "" && m.find(s) == m.end()){ 
                v[pattern[i]-'a'] = s;
                m[s] = pattern[i];
            }
            else{ 
                if(v[pattern[i]-'a'] != s || m[s] != pattern[i]) return false;
            }
            j = t;
        }
        return i == l1 && j == l2;
    }
};

No comments :

Post a Comment