290. Word Pattern
Given apattern
and a stringstr
, find ifstr
follows the same pattern.
Herefollowmeans a full match, such that there is a bijection between a letter inpattern
and anon-emptyword instr
.
Examples:
- pattern = "abba", str = "dog cat cat dog" should return true.
- pattern = "abba", str = "dog cat cat fish" should return false.
- pattern = "aaaa", str = "dog cat cat dog" should return false.
- pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assumepattern
contains only lowercase letters, andstr
contains lowercase letters separated by a single space.
S: istringstream + hashmap
bool wordPattern(string pattern, string str) {
unordered_map<char, string> charToStr;
unordered_set<string> strs;
istringstream s(str);
string word;
int idx = 0;
while (s >> word) {
if (idx == pattern.size()) return false;
if (charToStr.find(pattern[idx]) == charToStr.end()) {
if (strs.find(word) == strs.end()) {
charToStr[pattern[idx]] = word;
strs.insert(word);
} else {
return false;
}
} else if (charToStr[pattern[idx]] != word) {
return false;
}
idx++;
}
return idx == pattern.size();
}