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.
跟前面一篇博文类似,都是用map来检查单词是否已经处理过,代码如下:
class Solution {
public:
bool wordPattern(string pattern, string str) {
stringstream ss(str);
vector<string> tmpVec;
string tmp;
while(ss >> tmp)
tmpVec.push_back(tmp);
if(tmpVec.size() != pattern.size())
return false;
map<char, string> m1;
map<string, char> m2;
for(int i = ; i < pattern.size(); ++i){
tmp = tmpVec[i];
if(m1.find(pattern[i]) == m1.end() && m2.find(tmp) == m2.end()){
m1[pattern[i]] = tmp;
m2[tmp] = pattern[i];
}else if(m1.find(pattern[i]) != m1.end() && m2.find(tmp) != m2.end()){
if(m1[pattern[i]] != tmp || m2[tmp] != pattern[i])
return false;
}else{
return false;
}
}
return true;
}
};