题意:
* 给定一个pattern和一个字符串str,找到如果str遵循相同的模式。
* pattern = "abba",str = "dog cat cat dog"应该返回true。
* pattern = "abba",str = "dog cat cat fish"应该返回false。
leetcode给的答案:
public static boolean wordPattern(String pattern, String str) {
String[] words = str.split(" "); //分割开str这个字符串
if (words.length != pattern.length()) //如果长度不同,明显不符合题意,返回false
return false;
Map index = new HashMap(); //用map的解释见下边的分析
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
//修改后
public static boolean wordPattern1(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (!Objects.equals(index.put(pattern.charAt(i), i), index.put(words[i], i)))//修改后
return false;
return true;
}
分析:
Map的性质是:执行put函数时,如果key值存在,则覆盖key对应的value,并返回旧的value。本方法就用到了该性质,分析返回的值是否相等,判断两个字符串是不是按位对应关系,如下: