290. Word Pattern

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
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] strs = s.split(" ");
if (strs.length != pattern.length()) {
return false;
}

Map<Character, String> fromToMap = new HashMap<>();
Map<String, Character> toFromMap = new HashMap<>();

for (int i = 0; i < pattern.length(); i++) {
char from = pattern.charAt(i);
String to = strs[i];
String exceptedTo = fromToMap.get(from);
if (exceptedTo != null && !exceptedTo.equals(to)) {
return false;
}
Character exceptedFrom = toFromMap.get(to);
if (exceptedFrom != null && exceptedFrom != from) {
return false;
}
fromToMap.put(from, to);
toFromMap.put(to, from);
}

return true;
}
}

References

290. Word Pattern