LeetCode 290. Word Pattern

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public boolean wordPattern(String pattern, String str) {
Map<String, Character> str2ch = new HashMap<>();
Map<Character, String> ch2str = new HashMap<>();
int n = str.length();
int i = 0;
for (char ch : pattern.toCharArray()) {
if (i >= n) return false;
int j = i;
while (j < n && str.charAt(j) != ' ') j++;
String tmp = str.substring(i, j);
if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) return false;
if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) return false;
str2ch.put(tmp, ch);
ch2str.put(ch, tmp);
i = j + 1;
}
return i >= n;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, int> p2i;
unordered_map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
word2ch = dict()
ch2word = dict()
words = s.split()
if len(pattern) != len(words): return False
for ch, word in zip(pattern, words):
if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
return False
word2ch[word] = ch
ch2word[ch] = word
return True