哈希表,需要注意的是pattern中字符个数和s中单词个数不相等的情况
class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char, string> map_p2s;
unordered_map<string, char> map_s2p;
int j = 0;
int size = s.size();
int num = 0;
for(char c : pattern){
string temp;
while(j < size && s[j] != ' '){
temp.push_back(s[j++]);
}
if(temp != "") num++;
j++;
if(map_p2s.find(c) != map_p2s.end() && map_p2s[c] != temp) return false;
if(map_s2p.find(temp) != map_s2p.end() && map_s2p[temp] != c) return false;
map_p2s[c] = temp;
map_s2p[temp] = c;
}
//处理pattern中字符个数和s中单词个数不相等的case
if(num != pattern.size() || j < size) return false;
return true;
}
};