-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord Pattern.java
More file actions
31 lines (25 loc) · 882 Bytes
/
Copy pathWord Pattern.java
File metadata and controls
31 lines (25 loc) · 882 Bytes
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
https://leetcode.com/problems/word-pattern/
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) {
return false;
}
Map<Character, String> charToWord = new HashMap<>();
Map<String, Character> wordToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
if (!charToWord.containsKey(c)) {
charToWord.put(c, word);
}
if (!wordToChar.containsKey(word)) {
wordToChar.put(word, c);
}
if (!charToWord.get(c).equals(word) || !wordToChar.get(word).equals(c)) {
return false;
}
}
return true;
}
}