
Solution
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] strs = s.split(" ");
if (pattern.length() != strs.length) {
return false;
}
Map<Character, String> map1 = new HashMap<>();
Map<String, Character> map2 = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String str = strs[i];
if (!map1.containsKey(c)) {
map1.put(c, str);
} else if (!map1.get(c).equals(str)) {
return false;
}
if (!map2.containsKey(str)) {
map2.put(str, c);
} else if (map2.get(str) != c) {
return false;
}
}
return true;
}
}