给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", s = "dog cat cat dog"
输出: true
解法一 :用stringstream处理有空格的字符串
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> map;
unordered_map<string, char> rmap;
stringstream ss(str); string s;
for(char c : pattern) {
if(!(ss >> s) || (map.count(c) == 1 && map[c] != s) || (rmap.count(s) == 1 && rmap[s] != c)) return false;
map[c] = s; rmap[s] = c;
}
return (ss >> s) ? false : true;
}
};
解法二
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> mymap;
unordered_map<string,char> mymap1;
int index = 0;
int l = 0;
int r = 0;
while(r < s.size()){
while(r < s.size() && s[r] != ' '){
r++;
}
string tmp = s.substr(l,r-l);
if(mymap.find(pattern[index]) == mymap.end()){
mymap[pattern[index]] = tmp;
}else{
if(mymap[pattern[index]] != tmp){
return false;
}
}
if(mymap1.find(tmp) == mymap1.end()){
mymap1[tmp] = pattern[index];
}else{
if(mymap1[tmp] != pattern[index]){
return false;
}
}
index++;
l = r;
l++;
r++;
}
return index < pattern.size() ? false:true;
}
};
标签:tmp,map,false,规律,index,pattern,单词,290,string
From: https://www.cnblogs.com/lihaoxiang/p/17838634.html