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:
  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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

思路

与Isomorphic String(http://www.jianshu.com/p/b98c10c95735)思路一致。

Corner Case:

  1. pattern 与 str为空
  2. str.split(" ") 以后的List长度与Pattern字符串长度不一致。
class Solution {
    public boolean wordPattern(String pattern, String str) {
        if ( pattern == null || str == null) {
            return false;
        }
        
        HashMap mapping = new HashMap<>();
        Set set = new HashSet();
        String[] strList = str.split(" ");
        
        if (pattern.length() != strList.length) {
            return false;
        }
        
        for (int i = 0; i < pattern.length(); i++) {
            if (!mapping.containsKey(pattern.charAt(i))) {
                if (set.contains(strList[i])) {
                    return false;
                }
                mapping.put(pattern.charAt(i), strList[i]);
                set.add(strList[i]);
            } else {
                if (!mapping.get(pattern.charAt(i)).equals(strList[i])) {
                    return false;
                }
            }
        }
        return true;
    }
}

你可能感兴趣的:(Word Pattern)