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来检查单词是否已经处理过,代码如下:
1 class Solution { 2 public: 3 bool wordPattern(string pattern, string str) { 4 stringstream ss(str); 5 vector<string> tmpVec; 6 string tmp; 7 while(ss >> tmp) 8 tmpVec.push_back(tmp); 9 if(tmpVec.size() != pattern.size()) 10 return false; 11 map<char, string> m1; 12 map<string, char> m2; 13 for(int i = 0; i < pattern.size(); ++i){ 14 tmp = tmpVec[i]; 15 if(m1.find(pattern[i]) == m1.end() && m2.find(tmp) == m2.end()){ 16 m1[pattern[i]] = tmp; 17 m2[tmp] = pattern[i]; 18 }else if(m1.find(pattern[i]) != m1.end() && m2.find(tmp) != m2.end()){ 19 if(m1[pattern[i]] != tmp || m2[tmp] != pattern[i]) 20 return false; 21 }else{ 22 return false; 23 } 24 } 25 return true; 26 } 27 };