[LeetCode] Word Pattern

290. Word Pattern

Given a pattern and a string s, find if s 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 s.

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
class Solution {
unordered_map<char, string> mp;
unordered_map<string, char> rmp;
string parse(string& s, int& i) {
string res = "";
while(i < s.length() and s[i] != ' ') {
res += s[i++];
}
i++;
return res;
}
public:
bool wordPattern(string pattern, string s) {
int i = 0;
for(auto& p : pattern) {
if(i >= s.length()) return false;
string match = parse(s,i);
if(mp.count(p) and mp[p] != match)
return false;
if(rmp.count(match) and rmp[match] != p)
return false;
rmp[match] = p;
mp[p] = match;
}
return i >= s.length();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/07/PS/LeetCode/word-pattern/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.