2015年10月15日星期四

Word Pattern II

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 substring in str.
Examples:

  1. pattern = "abab", str = "redblueredblue" should return true.
  2. pattern = "aaaa", str = "asdasdasdasd" should return true.
  3. pattern = "aabb", str = "xyzabcxzyabc" should return false.


Notes:
You may assume both pattern and str contains only lowercase letters.

public class Solution {
    public boolean wordPatternMatch(String pattern, String str) {
        if (pattern == null || str == null) return false;
        return helper(pattern, str, 0, 0, new HashMap<>(), new HashSet<>());
    }
   
    private boolean helper(String pattern, String str, int p, int q, HashMap<Character, String> map, HashSet<String> set) {
        if (p == pattern.length() && q == str.length()) {
            return true;
        } else if (p < pattern.length() && q < str.length()) {
            char c = pattern.charAt(p);
            if (map.containsKey(c)) {
                String s = map.get(c);
                if (str.substring(q).startsWith(s)) {
                    return helper(pattern, str, p + 1, q + s.length(), map, set);
                }
            } else {
                for (int i = q; i < str.length(); i++) {
                    String s = str.substring(q, i + 1);
                    if (set.contains(s)) continue;
                    map.put(c, s);
                    set.add(s);
                    if (helper(pattern, str, p + 1, i + 1, map, set)) return true;
                    map.remove(c);
                    set.remove(s);
                }
            }
        }
        return false;
    }
}

没有评论:

发表评论