Cover image for Interview Classic 150 Questions P290 Word Pattern

Interview Classic 150 Questions P290 Word Pattern


Timeline

timeline

2025-11-13

init

hash table

Title:

Use a hash table to represent the mapping relationship. If a character and a string have not been mapped or have been mapped, map them. If a character has been mapped, then the current string must be the mapped string.

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)
{
int i, n = pattern.size();
vector<string> s_vec;
stringstream ss(s);
string curr;

while (ss >> curr)
s_vec.push_back(curr);

if (s_vec.size() != n) return false;

unordered_map<char, string> p2smap;
unordered_map<string, char> s2pmap;

for (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;
}
};