哈希表
- 思路
- pattern 每个字符映射 s 的一个单词,使用两个 map,存放<字符 -> 单词> 和 <单词 -> 字符>,遍历 pattern 的字符,如果查找出对应的单词和字符能够匹配即符合规律;
- 扣出 s 字符串的单词
-
// idx is the begin of the word // end is the right border int end = idx; while (end < size && s[end] != ' ') { end++; } // the begin and the size to get the word from s with substr const std::string &word = s.substr(idx, end - idx);
-
- 相互验证映射关系,如果不符合,则不符合规律;
-
// word not map the char if (str2ch.count(word) && str2ch[word] != ch) { return false; } // nor the ch not map the word if (ch2str.count(ch) && ch2str[ch] != word) { return false; } // build the map str2ch[word] = ch; ch2str[ch] = word;
-
- 完整代码:
class Solution {
public:
bool wordPattern(string pattern, string s) {
std::unordered_map<char, std::string> ch2str;
std::unordered_map<std::string, char> str2ch;
int size = s.size();
int idx = 0;
for (auto ch : pattern) {
if (idx >= size) {
return false;
}
int end = idx;
while (end < size && s[end] != ' ') {
end++;
}
const std::string &word = s.substr(idx, end - idx);
if (str2ch.count(word) && str2ch[word] != ch) {
return false;
}
if (ch2str.count(ch) && ch2str[ch] != word) {
return false;
}
str2ch[word] = ch;
ch2str[ch] = word;
idx = end + 1;
}
return idx >= size;
}
};