-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_wordpattern.cpp
More file actions
44 lines (37 loc) · 1.22 KB
/
01_wordpattern.cpp
File metadata and controls
44 lines (37 loc) · 1.22 KB
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
//https://leetcode.com/problems/word-pattern/description/
class Solution {
public:
bool wordPattern(string pattern, string s)
{
map<char, string>chToWordMap;
map<string, char>wordToChMap;
s.push_back(' ');
string currWord = "";
int chIdx = 0;
for (int i = 0; i < s.size(); i++)
{
if(s[i] == ' ')
{
char currCh = pattern[chIdx++];
if (chToWordMap.count(currCh))
{
string alreadyMappedWord = chToWordMap[currCh];
if (alreadyMappedWord != currWord) return false;
}
else if (wordToChMap.count(currWord))
{
char alreadyMappedCh = wordToChMap[currWord];
if (alreadyMappedCh != currCh) return false;
}
else
{
chToWordMap[currCh] = currWord;
wordToChMap[currWord] = currCh;
}
currWord = "";
}
else currWord.push_back(s[i]);
}
return (chIdx == pattern.size());
}
};