Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
s思路:
1. 由于是一一映射,所以需要两个hash分别负责从pattern->str,str->pattern的映射
2. 另外需要take care of the length consistence. In other words, the two should have the same length.
//方法1:hash
class Solution {
public:
bool wordPattern(string pattern, string str) {
//
int n=str.size();
unordered_map<string,string> mm1,mm2;
int count=0;
for(int i=0;i<str.size();i++){
if(count>=n) return false;
if(str[i]==' '){
count++;
continue;
}
int j=i;
while(j<str.size()&&str[j]!=' '){
j++;
}
string cur=str.substr(i,j-i);
string p=pattern.substr(count,1);
if(mm1.count(cur)&&mm2.count(p)){
if(mm1[cur]!=p&&mm2[p]!=cur) return false;
}else if((mm1.count(cur)==0)&&(mm2.count(p)==0)){
mm1[cur]=p;
mm2[p]=cur;
}else
return false;
i=j-1;
}
return count==pattern.size()-1;
}
};