-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode290.cpp
50 lines (48 loc) · 1.21 KB
/
leetcode290.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char, string> mp1;
map<string, char> mp2;
vector<string> vec;
int len = str.size();
string word("");
for (int i = 0; i < len; ++i)
{
if(str[i] == ' ')
{
vec.push_back(word);
word = "";
}
else
{
word += str[i];
}
if(i == len -1)
{
vec.push_back(word); //push_back the last word
}
}
int n = pattern.size();
if(vec.size() != n) return false;
for (int i = 0; i < n; i++)
{
map<char, string>::iterator mp1Ite;
map<string, char>::iterator mp2Ite;
mp1Ite = mp1.find(pattern[i]);
mp2Ite = mp2.find(vec[i]);
if(mp1Ite == mp1.end() && mp2Ite == mp2.end())
{
mp1[pattern[i]] = vec[i];
mp2[vec[i]] = pattern[i];
}
else if(mp1Ite != mp1.end() && mp2Ite != mp2.end())
{
if(mp1[pattern[i]] != vec[i] || mp2[vec[i]] != pattern[i])
return false;
}
else
return false;
}
return true;
}
};