题目:
用哈希表表示映射关系,如果一个字符和一个字符串没有映射过或被映射过,就映射它们。如果一个字符被映射过了,那么当前字符串一定得是被映射的字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <string> #include <vector> #include <sstream> #include <unordered_map>
using std::string; using std::unordered_map; using std::vector; using std::stringstream;
class Solution { public: bool wordPattern(string pattern, string s) { vector<string> s_vec; stringstream ss(s); string curr; while (ss >> curr) { s_vec.push_back(curr); } int n = pattern.size(); if (s_vec.size() != n) { return false; } unordered_map<char, string> p2smap; unordered_map<string, char> s2pmap; for (int i = 0; i < n; i++) { if (!p2smap.count(pattern[i]) && !s2pmap.count(s_vec[i])) { p2smap[pattern[i]] = s_vec[i]; s2pmap[s_vec[i]] = pattern[i]; } else { if (p2smap[pattern[i]] != s_vec[i] || s2pmap[s_vec[i]] != pattern[i]) { return false; } } } return true; } };
|