Leetcode 291. Word Pattern II

在这里插入图片描述
方法1: 这道题一看也是recursion/dfs/backtracking,我自己的思路也和正确思路一模一样。可是在实现起来的时候并不是那么简单,各种逻辑怎么合理的组织起来真的是很费劲,并且base case怎么写也不是一件容易的事。但是我比较开心的是至少我的思路是一模一样的。我在discussion区看到了一个和我思路一模一样而且解释的特别清晰的帖子,附上链接

public class Solution {
    
    
  
  public boolean wordPatternMatch(String pattern, String str) {
    
    
    Map<Character, String> map = new HashMap<>();
    Set<String> set = new HashSet<>();
    
    return isMatch(str, 0, pattern, 0, map, set);
  }
  
  boolean isMatch(String str, int i, String pat, int j, Map<Character, String> map, Set<String> set) {
    
    
    // base case
    if (i == str.length() && j == pat.length()) return true;
    if (i == str.length() || j == pat.length()) return false;
    
    // get current pattern character
    char c = pat.charAt(j);
    
    // if the pattern character exists
    if (map.containsKey(c)) {
    
    
      String s = map.get(c);
      
      // then check if we can use it to match str[i...i+s.length()]
      if (!str.startsWith(s, i)) {
    
    
        return false;
      }
      
      // if it can match, great, continue to match the rest
      return isMatch(str, i + s.length(), pat, j + 1, map, set);
    }
    
    // pattern character does not exist in the map
    for (int k = i; k < str.length(); k++) {
    
    
      String p = str.substring(i, k + 1);

      if (set.contains(p)) {
    
    
        continue;
      }

      // create or update it
      map.put(c, p);
      set.add(p);
      
      // continue to match the rest
      if (isMatch(str, k + 1, pat, j + 1, map, set)) {
    
    
        return true;
      }

      // backtracking
      map.remove(c);
      set.remove(p);
    }
    
    // we've tried our best but still no luck
    return false;
  }
  
}

** 总结:**

  • 复盘的时候自己去实现一遍,我现在没实现。

猜你喜欢

转载自blog.csdn.net/GoodJobJasper/article/details/112856713