Leetcode 290. Word Pattern

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Word Pattern

2. Solution

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
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> strs;
split(str, strs);
if(pattern.size() != strs.size()) {
return false;
}
unordered_map<char, string> m1;
unordered_map<string, char> m2;
for(int i = 0; i < pattern.length(); i++) {
if(m1.find(pattern[i]) == m1.end()) {
m1[pattern[i]] = strs[i];
}
else if(m1[pattern[i]] != strs[i]) {
return false;
}
if(m2.find(strs[i]) == m2.end()) {
m2[strs[i]] = pattern[i];
}
else if(m2[strs[i]] != pattern[i]) {
return false;
}
}
return true;
}

private:
void split(string& str, vector<string>& strs) {
int start = 0;
for(int i = 0; i < str.length(); i++) {
if(str[i] == ' ') {
strs.push_back(str.substr(start, i - start));
start = i + 1;
}
}
strs.push_back(str.substr(start, str.length() - start));
}
};

Reference

  1. https://leetcode.com/problems/word-pattern/description/
如果有收获,可以请我喝杯咖啡!