-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathword-pattern.cpp
36 lines (27 loc) · 973 Bytes
/
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
class Solution {
public:
bool wordPattern(string pattern, string s) {
s += " ";
vector<string> tokens;
int startIndex = 0;
for(int i = 0; i < s.size(); i++ ) {
if ( s[i] == ' ' ) {
tokens.push_back(s.substr(startIndex, i - startIndex));
startIndex = i + 1;
}
}
if ( pattern.size() != tokens.size() ) { return false; }
map<char, string> charMap;
map<string, char> strMap;
for(int i = 0; i < pattern.size(); i++) {
if ( charMap.count(pattern[i]) == 0 && strMap.count(tokens[i]) == 0) {
charMap[pattern[i]] = tokens[i];
strMap[tokens[i]] = pattern[i];
}
if ( tokens[i] != charMap[pattern[i]] ) {
return false;
}
}
return true;
}
};