-
Notifications
You must be signed in to change notification settings - Fork 0
/
200711-1.cpp
57 lines (55 loc) · 1.39 KB
/
200711-1.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
// https://leetcode-cn.com/problems/word-pattern/
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = split(str);
if (pattern.size() != words.size()) {
return false;
}
unordered_map<char, string> m;
unordered_set<string> m2;
for (int i = 0; i < pattern.size(); ++i) {
char c = pattern[i];
string w = words[i];
if (m.find(c) == m.end()) {
if (m2.find(w) != m2.end()) return false;
m[c] = w;
m2.insert(w);
} else {
if (m[c] != w) return false;
}
}
return true;
}
private:
vector<string> split(string str) {
vector<string> words;
string s;
for (auto c : str) {
if (c == ' ') {
if (!s.empty()) words.push_back(s);
s.clear();
} else {
s += c;
}
}
if (!s.empty()) words.push_back(s);
return words;
}
};
int main() {
Solution s;
cout << s.wordPattern("abba", "dog cat cat dog") << endl; // answer: true
cout << s.wordPattern("abba", "dog cat cat fish") << endl; // answer: false
cout << s.wordPattern("aaaa", "dog cat cat dog") << endl; // answer: false
cout << s.wordPattern("abba", "dog dog dog dog") << endl; // answer: false
cout << s.wordPattern("aaa", "aa aa aa aa") << endl; // answer: false
cout << s.wordPattern("a", "a") << endl; // answer: true
return 0;
}