-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_pattern.cpp
36 lines (35 loc) · 1.04 KB
/
word_pattern.cpp
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
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> match;
int s_traverse = 0;
string word = "";
while (s_traverse < s.length()) {
if (s[s_traverse] == ' '){
match.push_back(word);
word = "";
} else {
word += s[s_traverse];
}
s_traverse++;
}
match.push_back(word);
if (pattern.length() != match.size()) {
return false;
}
unordered_map <char, string> word_pattern;
for (int i = 0; i < pattern.length(); ++i) {
for (auto itr: word_pattern) {
if ((itr.first == pattern[i]) && (itr.second != match[i])) {
return false;
}
if ((itr.second == match[i]) && (itr.first != pattern[i])) {
return false;
}
}
word_pattern[pattern[i]] = match[i];
}
return true;
}
};