class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.length) {
return false;
}
Map<Object, Integer> map = new HashMap<>();
// 注意循环体i用Integer,完成提前的装箱,否则但i=128,在map的put中自动装箱,会溢出,因为Java中自动装箱是调用Integer.valueOf(int i)方法,值范围为[-128,127]
for (Integer i = 0; i < words.length; i ++) {
// 利用Java中Map的put方法特性,放入一个已存在的key,会返回旧key的索引,否则返回null
if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) {
return false;
}
}
return true;
}
}