/*class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> m;
int a = 0;
for(int i = 0;i < pattern.size();i++){
while(isspace(s[a]))
a++;
int b = a;
while(isalpha(s[a]))
a++;
if(m.find(pattern[i]) == m.end()){
m[pattern[i]] = s.substr(b,a-b);
}
else if(m[pattern[i]] != s.substr(b,a-b))
return false;
}
return true;
}
};
//"abba"
//"dog dog dog dog"
//依然还是双向映射问题
*/
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> m1;
unordered_map<string,char> m2;
int count = 0;//用于统计子串的总个数,子串的种个数必须与 pattern 的长度一致
int a = 0;
for(int i = 0;i < pattern.size();i++){
while(isspace(s[a]))
a++;
int b = a;
while(isalpha(s[a]))
a++;
string str = s.substr(b,a-b);
count++;
if(m1.find(pattern[i]) == m1.end() && m2.find(str) == m2.end()){
m1[pattern[i]] = str;
m2[str] = pattern[i];
}
else if(m1[pattern[i]] != str || m2[str] != pattern[i])
return false;
}
return count == pattern.size() && a == s.size();
}
//"aaa"
//"aa aa aa aa"
};
正确的解法
1、双向映射
2、s子串的个数必须与 pattern 的长度一致
3、s 的子串不能为空。可能会存在 pattern 的长度比 s 的子串个数长,最后放入的子串都为空了。
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char,string> m1;
unordered_map<string,char> m2;
int count = 0;//用于统计子串的总个数,子串的种个数必须与 pattern 的长度一致
int a = 0;
for(int i = 0;i < pattern.size();i++){
while(isspace(s[a]))
a++;
int b = a;
while(isalpha(s[a]))
a++;
string str = s.substr(b,a-b);
if(str == "")
break;
count++;
if(m1.find(pattern[i]) == m1.end() && m2.find(str) == m2.end()){
m1[pattern[i]] = str;
m2[str] = pattern[i];
}
else if(m1[pattern[i]] != str || m2[str] != pattern[i])
return false;
}
return count == pattern.size() && a == s.size();
}
//"aaa"
//"aa aa aa aa"
//"he"
//"unit"
};