Simple solution if using a map to store the association between a character of “pattern” and a word from “str”. Remember to rule out the case in which different characters in pattern mapped to the same word in str. For example, “abba” -> “dog dog dog dog” is FALSE.
Another solution with less space:
using the “put” function of “map” in Java. Put(key, value) returns the last value of the current key. Check out the code:
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(” “);
if (words.length != pattern.length()) return false;
Map map = new HashMap(); // do not specify type for map, which takes character and string as keys
for (Integer i = 0 ; i < words.length; i++) { // Integer here makes a difference, cannot use int
if (map.put(words[i], i) != map.put(pattern.charAt(i), i)) {
return false;
}
}
return true;
}
In the above code, Integer CANNOT be replaced by int. When using int, the returned value of “put” is int, and Java autobox the int value into different Integer objects, so that the comparison “map.put(words[i], i) != map.put(pattern.charAt(i), i)” does not work normally. This is the “autoboxing-same-value-to-different-objects” problem.
Advertisements