Leetcode - Word Pattern II

My code:

import java.util.HashMap;
import java.util.HashSet;

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 p, String s, int index, int begin, HashMap map, HashSet set) {
        if (index == p.length() && begin == s.length()) {
            return true;
        }
        else if (index == p.length() || begin == s.length()) {
            return false;
        }
        
        char curr = p.charAt(index);
        if (map.containsKey(curr)) {
            String val = map.get(curr);
            if (s.substring(begin).startsWith(val)) {
                return helper(p, s, index + 1, begin + val.length(), map, set);
            }
            else {
                return false;
            }
        }
        else {
            for (int i = begin; i < s.length(); i++) {
                String next = s.substring(begin, i + 1);
                if (set.contains(next)) {
                    continue;
                }
                else {
                    set.add(next);
                    map.put(curr, next);
                    boolean flag = helper(p, s, index + 1, begin + next.length(), map, set);
                    if (flag) {
                        return true;
                    }
                    set.remove(next);
                    map.remove(curr);
                }
            }
            return false;
        }
    }
}

reference:
https://discuss.leetcode.com/topic/26750/share-my-java-backtracking-solution/2

这道题目没能做出来不应该的。
其实和
Regular Expression
Wildcard Matching
很相似,都是 pattern match的问题。然后都需要 backtracking

只不过我一开始想的是,string 做key, character 做value
这样的话,每次dfs,对于string,就需要传入begin, end两个参数。有点麻烦
然后这里的话反了下。
好处是,
当我们拿到这一层的character 时,如果hashtable中存在这个key,那么取出value,判断当前string是否 startsWith(value)
如果是,就进入下一级,如果不是,就返回false

如果hashtable 不存在这个key
那么就需要用 backtracking 标志性的 for-loop
遍历每种情况。
同时,不同的key不同映射到同个string,用这个条件可以减去some branch to reduce the time

差不多就这样了。

Anyway, Good luck, Richardo! -- 09/19/2016

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