[LC 290] Word pattern

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s