题目来源
题目描述
题目解析
一个map
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> map;//考察哈希表
int i=0;
istringstream iss(s);//考察string的io操作
string word;
while(iss>>word){ //利用istringstream可以按空格读取的特性
if(i==pattern.size())return false;//两个字符串不一样长的话,s更长的情况
//不匹配情况1:a想同时映射dog和fish
/* 例子
"abba"
"dog cat cat fish"
*/
else if(map.find(pattern[i])!=map.end()&&map[pattern[i]]!=word)return false;//考察哈希表的find操作和迭代器
//不匹配情况2:dog想同时映射a和b
/* 例子
"abba"
"dog dog dog dog"
*/
//考察哈希表的find_if操作及lambda表达式
else if(map.find(pattern[i])!=find_if(begin(map),end(map),[&](const pair<char,string>& p){return p.second==word;}))return false;
else map[pattern[i]]=word;
++i;
}
if(i!=pattern.size())return false;//两个字符串不一样长的话,s更短的情况
return true;
}
};
类似题目
题目 | 思路 |
---|---|
leetcode:205. 同构字符串 Isomorphic Strings | |
leetcode:290. 单词规律 Word Pattern |