-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathword-pattern.cpp
68 lines (58 loc) · 1.5 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://leetcode.com/problems/word-pattern/
class Solution
{
public:
vector<string> splitString(string str, string delimiter)
{
vector<string> vectorStr;
int start = 0;
int end = str.find(delimiter);
while (end != -1)
{
vectorStr.push_back(str.substr(start, end - start));
start = end + delimiter.size();
end = str.find(delimiter, start);
}
vectorStr.push_back(str.substr(start, end - start));
return vectorStr;
}
bool wordPattern(string pattern, string s)
{
vector<string> vectorString;
vectorString = splitString(s, " ");
int patternLength = pattern.length();
int vectorLength = vectorString.size();
if (patternLength != vectorLength)
{
return false;
}
// Mapping from left to right
map<char, string> charToWord;
map<char, string>::iterator itrFirst;
// Mapping from right to left
map<string, char> wordToChar;
map<string, char>::iterator itrSecond;
for (int i = 0; i < patternLength; i++)
{
itrFirst = charToWord.find(pattern[i]);
if ((itrFirst != charToWord.end()) && (itrFirst->second != vectorString[i]))
{
return false;
}
itrSecond = wordToChar.find(vectorString[i]);
if ((itrSecond != wordToChar.end()) && (itrSecond->second != pattern[i]))
{
return false;
}
if (itrFirst == charToWord.end())
{
charToWord.insert(pair<char, string>(pattern[i], vectorString[i]));
}
if (itrSecond == wordToChar.end())
{
wordToChar.insert(pair<string, char>(vectorString[i], pattern[i]));
}
}
return true;
}
};