Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
- pattern =
"abba", str ="dog cat cat dog"should return true. - pattern =
"abba", str ="dog cat cat fish"should return false. - pattern =
"aaaa", str ="dog cat cat dog"should return false. - pattern =
"abba", str ="dog dog dog dog"should return false.
class Solution {
public boolean wordPattern(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 (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
}
这份代码是是讨论区大神的代码,利用的是hashmap.put的思想,每次放进一个KV,put会返回k的上一次的索引值。下图是从别人那里截来方便说明。

根据pattern的字符,相同的k更新不同的v,同样的的word也是一样的更新。
e.g: pattern (abba) str (app dog dog app) 对应的map.put存值
i = 0: a,0 app 0 null
i = 1 :a 0,b 1 app 0, dog 1 null
i =2: a 0, b 2 app 0, dog 2 1
i = 3: a 3,b 2 app 3, dog 2 0
接下来,是本道题的一个重要问题。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String pattern = "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdd";
String str = "s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s t t";
boolean flag ;
flag = wordPattern(pattern,str);
System.out.println(flag);
}
public static boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map mp = new HashMap();
Map mw = new HashMap();
// for(intager i = 0;i<pattern.length():i++)
for(int i = 0; i<pattern.length();i++){
if(mp.put(pattern.charAt(i),i)!=mw.put(words[i],i)){
return false;
}
}
return true;
}
}
这个代码参数数量是129,当用int i是返回值是false,用integer i时返回值是true。正确答案是true。
出现这种情况的原因是,jvm对int在-128 ~ 127 会有一个缓存操作,换句话说int类型在这个范围内用的是一个integer对象,超出这个范围就会重新new一个新的。
而i=会进行对象的比较,所以即使数值相同,地址不同,就会出现错误。

前者是int类型,超过127以后地址已经不同了,后者是integer类型,地址不变。
当然也可以采用equals,它只是取内容。

浙公网安备 33010602011771号