-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path290_Word_Pattern.cc
36 lines (36 loc) · 1.05 KB
/
290_Word_Pattern.cc
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 str) {
vector<string> word=splitStr(str);
if(pattern.size()!=word.size()) return false;
unordered_map<char,int> mapping;
unordered_map<string,int> wordmapping;
for(int i=0;i<pattern.size();++i){
if(mapping.find(pattern[i])!=mapping.end()){
if(word[mapping[pattern[i]]]!=word[i]){
return false;
}
}
else{
if(wordmapping.find(word[i])!=wordmapping.end()) return false;
mapping[pattern[i]]=i;
wordmapping[word[i]]=i;
}
}
return true;
}
private:
vector<string> splitStr(string str){
vector<string> result;
string word="";
for(int i=0;i<str.size();++i){
if(str[i]==' '){
result.push_back(word);
word="";
}
else word+=str[i];
}
result.push_back(word);
return result;
}
};