解题思路
首先将单词字符串保存在一个字符串数组中,用
split(" ")来进行分割。然后将这pattern数组和
字符串数组来进行同步比较。
1 containsKey();
2 containsValue();
3 isEmpty(); //哈希表为空
4 split(" "); //依靠" "来分割数组
相关代码
class Solution {
public boolean wordPattern(String pattern, String s) {
String str[] = s.split(" ");
if(pattern.length()!=str.length) return false;
Map<Character,String> hash = new HashMap<>();
for(int i=0,j=0;i<pattern.length();i++,j++){
char c1=pattern.charAt(i);
if(hash.isEmpty()==true){
hash.put(c1,str[j]);
}
else{
if(hash.get(c1)==null){
if(hash.containsValue(str[j])==true){
return false;
}
hash.put(c1,str[j]);
}
else{
if(hash.get(c1).equals(str[j])==false){
return false;
}
}
}
}
return true;
}
}