290. 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.

思路:跟205. Isomorphic Strings 思路完全相同, 唯一注意的是205中是char比较, 本题是String比较.

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (str == null || pattern == null) return false;
        String[] arr = str.split("\\s+");
        if (pattern.length() != arr.length) return false;
        HashMap<Character, String> map = new HashMap<>();
        HashSet<String> set = new HashSet<>();

        for (int i = 0; i < arr.length; i++) {
            Character c = pattern.charAt(i);
            String s = arr[i];
            if (!map.containsKey(c)) {
                if (set.contains(s)) {
                    return false;
                } else {
                    map.put(c, s);
                    set.add(s);
                }
            } else {
                String value = map.get(c);
                if (!value.equals(arr[i])) {
                    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