JAVA Backtracking solution


  • 0
    S
    public class Solution {
        private HashMap map = new HashMap();
        public boolean wordPatternMatch(String pattern, String str) {
            if (str == null || pattern == null) {
                return false;
            }
            return match(pattern, 0, str, 0);
        }
        
        public boolean match(String pattern, int pIndex, String str, int sIndex) {
            if (pIndex == pattern.length() && sIndex == str.length()) return true;
            if (pIndex >= pattern.length() || sIndex >= str.length()) return false;
           
            char c = pattern.charAt(pIndex);
            String value = (String) map.get(c);
            if (value != null) {
                if (str.startsWith(value, sIndex)) {
                    return match(pattern, pIndex + 1, str, sIndex + value.length());
                } else {
                    return false;
                }
            } else {
                for (int i = sIndex; i < str.length(); i++) {
                    String subString = str.substring(sIndex, i + 1);
                    if (!map.containsKey(subString)) {
                        map.put(c, subString);
                        map.put(subString, c);
                        if (match(pattern, pIndex + 1, str, i + 1)) {
                            return true;
                        } else {
                            map.remove(c);
                            map.remove(subString);
                        }
                    }
                }
                return false;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.