描述
给定一种规律 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/
求解
class Solution {
public:
// 方法一,双向散列表查找核对
bool wordPattern(string pattern, string s) {
std::unordered_map<char, string> record1;
std::unordered_map<string, char> record2;
vector<string> strvec;
split(s, strvec);
if (strvec.size() != pattern.size()) {
return false;
}
const int n = pattern.size();
for (int i = 0; i < n; ++i) {
if (record1.count(pattern[i]) == 0) {
record1.emplace(pattern[i], strvec[i]);
}
if (record2.count(strvec[i]) == 0) {
record2.emplace(strvec[i], pattern[i]);
}
if (record1[pattern[i]] != strvec[i]) {
return false;
}
if (record2[strvec[i]] != pattern[i]) {
return false;
}
}
return true;
}
private:
// 单词切割
void split(const string &str, std::vector<string> &strvec) {
strvec.clear();
string word;
std::istringstream is(str);
while (is >> word) {
strvec.emplace_back(word);
}
}
};