Cover image for Classic 150 Interview Questions P290 Word Pattern

Classic 150 Interview Questions P290 Word Pattern


Timeline

Timeline

2025-11-13

init

Hash table

Problem:

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.

123456789101112131415161718192021222324252627282930313233343536373839
#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;	}};
Loading comments…