-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path290.单词规律.cpp
56 lines (56 loc) · 1.3 KB
/
290.单词规律.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
/*
* @lc app=leetcode.cn id=290 lang=cpp
*
* [290] 单词规律
*/
#include "a_header.h"
// @lc code=start
class Solution
{
public:
bool wordPattern(string pattern,
string s)
{
vector<string> words;
string tmp;
for (size_t i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
{
if (tmp.length() > 0)
{
words.push_back(tmp);
tmp.clear();
}
continue;
}
tmp += s[i];
if (s.length() == i + 1)
{
words.push_back(tmp);
}
}
if (words.size() != pattern.length())
return false;
unordered_map<char, string> maps;
unordered_set<string> hasMapped;
int cnt = 0;
for (auto &ch : pattern)
{
if (maps.find(ch) == maps.end() && hasMapped.find(words[cnt]) == hasMapped.end())
{
hasMapped.insert(words[cnt]);
maps[ch] = words[cnt++];
}
else
{
if (maps[ch] != words[cnt++])
{
return false;
}
}
}
return true;
}
};
// @lc code=end