290. Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
方法1: double hash
思路:
用了一刷和205. Isomorphic Strings一样naive的双哈希表。205题当中还有一种比较巧妙的做法,通过vector来建立函数检查一一映射,这里由于单词没有明显对应的vector index,相当于需要hash一遍,和double hash的做法就差不多了。分四种情况讨论?反而更麻烦。
易错点
- 双向映射要保证一一对应
- 最后还要检查i == n是因为有可能pattern和str长度不一样,如果str先结束,此时i = n返回false,也就是i == n在防守的情况。但是如果pattern先结束,循环并不会停下来,由于pattern是string,pattern[i]也不会像vector一样出现heap-overflow,而是直接调取该内存位置的值建立映射,大概率会返回false。但是太随意了,还是检查一下size是否相等。
Input
“jquery”
“jquery”
Output
true
Expected
false
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> hash;
unordered_map<string, char> hash_r;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; i++){
if (hash.count(pattern[i]) == 0 && hash_r.count(word) == 0){
hash_r[word] = pattern[i];
hash[pattern[i]] = word;
}
else if (hash[pattern[i]] != word || hash_r[word] != pattern[i]){
return false;
}
}
return i == n;
}
};
方法2: one hash
思路:
每次不但遍历一遍hash看char是否存在,还要遍历一次hash中所有word看是否已经被映射到某个char。
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> hash;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; i++){
if (hash.count(pattern[i]) == 0){
for (auto a: hash){
if (word == a.second){
return false;
}
}
hash[pattern[i]] = word;
}
else if (hash[pattern[i]] != word){
return false;
}
}
return i == n;
}
};