LeetCode290_单词规律
标签:#哈希表 #字符串
Ⅰ. 题目
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
Ⅱ. 示例
· 示例1:
输入: pattern = “abba”, s = “dog cat cat dog”
输出: true
· 示例 2:
输入:pattern = “abba”, s = “dog cat cat fish”
输出: false
· 示例 3:
输入: pattern = “aaaa”, s = “dog cat cat dog”
输出: false
0. 个人方法
这题与上一题(205_同构字符串)是一样的,只需要把 s 中的单词分别看作单个映射单元即可。
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> single;
istringstream iss(s);
string word;
while (iss >> word) {
single.push_back(word);
}
if (single.size() != pattern.length())
return false;
unordered_map<char, string> PtoS;
for (int i=0; i<pattern.length(); ++i){
if (PtoS.find(pattern[i]) == PtoS.end())
{
PtoS[pattern[i]] = single[i];
}else{
if (PtoS[pattern[i]] != single[i])
return false;
}
}
unordered_map<string, char> StoP;
for (int i=0; i<pattern.length(); ++i){
if (StoP.find(single[i]) == StoP.end())
{
StoP[single[i]] = pattern[i];
}else{
if (StoP[single[i]] != pattern[i])
return false;
}
}
return true;
}
};