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.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.


public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern  == null && str == null) return true; 
        if (pattern == null || str == null) return false; 
        char[] chars = pattern.toCharArray(); 
        String[] tokens = str.split(" ");
        if (tokens.length != chars.length) return false; 
        
        //Use a map to store the mapping relationship 
        HashMap<Character, String> map = new HashMap<Character, String>(); 
        //Use a set to store the existed strings
        HashSet<String> tokenSet = new HashSet<String>(); 
        
        for (int i = 0; i < chars.length; i++) {
            if (!map.containsKey(chars[i]) && !tokenSet.contains(tokens[i])) {
                //put new relationship in the map
                map.put(chars[i], tokens[i]);
                //put the string in th set
                tokenSet.add(tokens[i]);
            } else if (map.containsKey(chars[i]) && map.get(chars[i]).equals(tokens[i])) {
                //new word satisfy the existing relationship
                continue; 
            } else {
                return false;    
            }
        }
        return true; 
    }
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s