[LeetCode]Word Pattern II

public class Solution {
    public boolean wordPatternMatch(String pattern, String str) {
        return helper(pattern, str, new HashMap<Character, String>(), new HashMap<String, Character>());
    }
    public boolean helper(String pattern, String str, HashMap<Character, String> map1, HashMap<String, Character> map2) {
        if (pattern.length() == 0 && str.length() == 0) {
            return true;
        }
        if (pattern.length() == 0 || str.length() == 0) {
            return false;
        }
        char ch = pattern.charAt(0);
        if (map1.containsKey(ch)) {
            String tmp = map1.get(ch);
            if (tmp.length() > str.length() || !tmp.equals(str.substring(0, tmp.length()))) {
                return false;
            } else {
                return helper(pattern.substring(1), str.substring(tmp.length()), map1, map2);
            }
        } else {
            for (int i = 1; i <= str.length(); i++) {
                if (map2.containsKey(str.substring(0, i))) {
                    continue;
                }
                map1.put(ch, str.substring(0, i));
                map2.put(str.substring(0, i), ch);
                if (helper(pattern.substring(1), str.substring(i), map1, map2)) {
                    return true;
                }
                map1.remove(ch);
                map2.remove(str.substring(0, i));
            }
        }
        return false;
    }
}

 

posted @ 2015-12-01 09:01  Weizheng_Love_Coding  阅读(137)  评论(0编辑  收藏  举报