-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay2.java
More file actions
35 lines (29 loc) · 1018 Bytes
/
Day2.java
File metadata and controls
35 lines (29 loc) · 1018 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
32
33
34
35
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.length) {
return false;
}
HashMap<Character, String> charToWord = new HashMap<>();
HashMap<String, Character> wordToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String word = words[i];
if (charToWord.containsKey(ch)) {
if (!charToWord.get(ch).equals(word)) {
return false;
}
} else {
charToWord.put(ch, word);
}
if (wordToChar.containsKey(word)) {
if (wordToChar.get(word) != ch) {
return false;
}
} else {
wordToChar.put(word, ch);
}
}
return true;
}
}