290. 单词规律

判断给定字符串是不是按照给定模式的短语, 例如"dog dog cat cat"就是"aabb"式的短语

思路: 用map记录模式字母与单词的对应关系, 如果发现不一致, 返回false, 否则返回true

注意: 模式中不同字母对应的单词不能相同

提示:

按照key查询map可以使用map自带的find()函数

按照value查询map可以使用find_if()函数

两者都返回迭代器

1
2
M.find(someKey);
find_if(M.begin(), M.end(), [&](const auto& kv){ /* ... */ });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
bool wordPattern(string pattern, string s) {
map<char, string> M;
vector<string> S;
char *p = strtok((char *)s.c_str(), " ");
if (p) do {
S.push_back(p);
} while (p = strtok(NULL, " "));

if (pattern.size() != S.size()) {
return false;
}

for (int i = 0; i < pattern.size(); i++) {
char ch = pattern[i];
if (M.find(ch) == M.end()) {
if (find_if(M.begin(),M.end(),[&](const auto&p){return p.second==S[i];})!=M.end()){
return false;
}
cout<<ch<<" "<<S[i]<<endl;
M[ch] = S[i];
} else if (M[ch] != S[i]) {
cout<<M[ch]<<" "<<S[i]<<endl;
return false;
}
}
return true;
}
};