-
Notifications
You must be signed in to change notification settings - Fork 0
/
290. Word Pattern.cpp
55 lines (44 loc) · 1.22 KB
/
290. 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
// https://leetcode.com/problems/word-pattern/
class Solution
{
public:
bool wordPattern(string pattern, string s)
{
vector<int> first;
vector<int> second;
unordered_map<char, int> letterValue;
unordered_map<string, int> wordValue;
vector<string> words = getWords(s);
int j = 0;
if (words.size() != pattern.length())
return false;
for (int i = 0; i < pattern.length(); ++i)
{
if (letterValue.find(pattern[i]) == letterValue.end())
letterValue[pattern[i]] = j;
if (wordValue.find(words[i]) == wordValue.end())
wordValue[words[i]] = j;
first.push_back(letterValue[pattern[i]]);
second.push_back(wordValue[words[i]]);
j++;
}
return first == second;
}
vector<string> getWords(string &sentence)
{
vector<string> words;
string word = "";
for (char &c : sentence)
{
if (c == ' ')
{
words.push_back(word);
word = "";
}
else
word += c;
}
words.push_back(word);
return words;
}
};