Created
January 29, 2018 14:18
-
-
Save s4553711/4b7f04d35eeb8a10c4d85b0ea40b96b1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool wordPattern(string pattern, string str) { | |
str += ' '; | |
int i = 0, j = 0, len1 = pattern.size(), len2 = str.size(); | |
unordered_map<char, string> hash1; | |
unordered_map<string, char> hash2; | |
while(i < len1 && j < len2) { | |
int pos = str.find(' ', j); | |
string s = str.substr(j, pos-j); | |
if (hash1.count(pattern[i]) && hash1[pattern[i]] != s) return false; | |
if (hash2.count(s) && hash2[s] != pattern[i]) return false; | |
hash1[pattern[i]] = s; | |
hash2[s] = pattern[i]; | |
i++, j = pos + 1; | |
} | |
return i == len1 && j == len2; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment