290. 单词规律
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = “abba”, str = “dog cat cat dog”
输出: true
示例 2:
输入:pattern = “abba”, str = “dog cat cat fish”
输出: false
示例 3:
输入: pattern = “aaaa”, str = “dog cat cat dog”
输出: false
示例 4:
输入: pattern = “abba”, str = “dog dog dog dog”
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-pattern。
- 题解
使用哈希表查询是否匹配的问题。并且题目已经给出pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律
。所以这里直接使用两个map进行双向映射的检查。
特殊情况的注意事项: pattern的size大于或者小于str中单词的数量。
bool wordPattern(string pattern, string s) {
unordered_map<char, string> ch2str;
unordered_map<string, char> str2ch;
int i = 0;
int str_size = s.size();
for (auto &ch : pattern) {
if (i >= str_size) return false;
int j = i;
while (j < str_size && s[j] != ' ') ++j;
string str_tmp = s.substr(i, j - i);
if (ch2str.find(ch) != ch2str.end() && ch2str[ch] != str_tmp) {
return false;
}
if (str2ch.find(str_tmp) != str2ch.end() && str2ch[str_tmp] != ch) {
return false;
}
ch2str[ch] = str_tmp;
str2ch[str_tmp] = ch;
i = j + 1;
}
return i >= str_size;
}