Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created January 29, 2018 14:18
Show Gist options
  • Save s4553711/4b7f04d35eeb8a10c4d85b0ea40b96b1 to your computer and use it in GitHub Desktop.
Save s4553711/4b7f04d35eeb8a10c4d85b0ea40b96b1 to your computer and use it in GitHub Desktop.
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