题目:
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.
采取的办法是建立两个map,相互映射。为什么用一个map不够?如果面对第4个例子,abba,dog dog dog dog,a和b都会映射到dog,因为你要保证1对1映射,那么可以采取反面映射过来。
class Solution {public: bool wordPattern(string pattern, string str) { unordered_mapdictP; unordered_map dictS; string buff; int idx = 0; for (int i = 0; i < pattern.size(); i++){ buff.clear(); while (idx < str.size() && str[idx] != ' '){ buff.push_back(str[idx++]); } if (buff.empty()) return false; idx++; if (dictP.find(pattern[i]) == dictP.end() && dictS.find(buff) == dictS.end()){ dictP[pattern[i]] = buff; dictS[buff] = pattern[i]; } else if (dictP[pattern[i]] != buff || dictS[buff] != pattern[i]) return false; } if (idx == 0 || idx < str.size()) return false; return true; }};