Skip to content

Commit b8dd7f9

Browse files
committed
word_pattern
1 parent 1d03761 commit b8dd7f9

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
210210
#### [283. Move Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators)
211211
#### [284. Peeking Iterator](https://github.com/hitzzc/go-leetcode/tree/master/peeking_iterator)
212212
#### [287. Find the Duplicate Number](https://github.com/hitzzc/go-leetcode/tree/master/find_the_duplicate_number)
213+
#### [290. Word Pattern](https://github.com/hitzzc/go-leetcode/tree/master/word_pattern)
213214

214215

215216

word_pattern/word_pattern.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <unordered_map>
2+
#include <string>
3+
#include <vector>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
bool wordPattern(string pattern, string str) {
9+
unordered_map<char, string> pattern_to_str;
10+
unordered_map<string, char> str_to_pattern;
11+
int i = 0;
12+
int start = 0;
13+
for (int j = 0; j <= str.size(); ++j){
14+
if (i >= pattern.size()) return false;
15+
if (j == str.size() || str[j] == ' ') {
16+
string sub = str.substr(start, j-start);
17+
if (pattern_to_str.count(pattern[i]) == 0 && str_to_pattern.count(sub) == 0) {
18+
pattern_to_str[pattern[i]] = sub;
19+
str_to_pattern[sub] = pattern[i];
20+
}else if (pattern_to_str.count(pattern[i]) != 0 && str_to_pattern.count(sub) != 0) {
21+
if (pattern_to_str[pattern[i]] != sub || str_to_pattern[sub] != pattern[i]) {
22+
return false;
23+
}
24+
}else {
25+
return false;
26+
}
27+
++i;
28+
start = j+1;
29+
}
30+
}
31+
if (i != pattern.size()) return false;
32+
return true;
33+
}
34+
};

0 commit comments

Comments
 (0)