-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy path290_Word_Pattern
More file actions
86 lines (70 loc) · 2.29 KB
/
290_Word_Pattern
File metadata and controls
86 lines (70 loc) · 2.29 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Leetcode 290: Word Pattern
Detailed video explanation: https://youtu.be/cwBUZKqH6sw
==========================================
C++:
----
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> char_map;
unordered_map<string, char> word_map;
stringstream s(str);
string word;
int n = pattern.size(), i = 0;
while(s >> word){
if(i == n) return false;
char c = pattern[i];
if(char_map.count(c) != word_map.count(word)) return false;
if(char_map.count(c)){
if( (word_map[word] != c) || (char_map[c] != word)) return false;
} else {
char_map.insert({c, word});
word_map.insert({word, c});
}
i++;
}
return i == n;
}
};
Java:
-----
class Solution {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> char_map = new HashMap();
Map<String, Character> word_map = new HashMap();
int n = pattern.length(), i = 0;
String[] words = str.split(" ");
if(n != words.length) return false;
while(i < n){
char c = pattern.charAt(i);
String word = words[i];
if(char_map.containsKey(c) != word_map.containsKey(word)) return false;
if(char_map.containsKey(c)){
if( (word_map.get(word) != c) || !(char_map.get(c).equals(word)) ) return false;
} else {
char_map.put(c, word);
word_map.put(word, c);
}
i++;
}
return i == n;
}
}
Python3:
--------
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
char_map, word_map = {}, {}
n, i = len(pattern), 0
words = str.split(" ")
if n != len(words): return False
while i < n:
c, word = pattern[i], words[i]
if (c in char_map) != (word in word_map): return False
if c in char_map:
if (word_map[word] != c) or (char_map[c] != word): return False
else:
char_map[c] = word
word_map[word] = c
i += 1
return i == n