-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_290.java
More file actions
27 lines (24 loc) · 862 Bytes
/
Copy pathP_290.java
File metadata and controls
27 lines (24 loc) · 862 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
package leetcode.easy;
import java.util.HashMap;
import java.util.Map;
public class P_290 {
public boolean wordPattern(String pattern, String str) {
final String[] words = str.split(" ");
if (pattern.length() != words.length) {
return false;
}
final Map<Character, String> map1 = new HashMap<>();
final Map<String, Character> map2 = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
if (!words[i].equals(map1.getOrDefault(pattern.charAt(i), words[i]))) {
return false;
}
if (pattern.charAt(i) != map2.getOrDefault(words[i], pattern.charAt(i))) {
return false;
}
map1.put(pattern.charAt(i), words[i]);
map2.put(words[i], pattern.charAt(i));
}
return true;
}
}