Word Pattern II 解答

Question

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.

Solution

Word Pattern 是用HashMap的containsKey()和containsValue()两个方法实现的。

但是对于Word Pattern II,我们并不知道怎样划分str,所以基本想法是“暴力搜索”即backtracking/DFS。这里DFS的存储对象不是常见的list,而是map.

 1 public class Solution {
 2     public boolean wordPatternMatch(String pattern, String str) {
 3         return helper(pattern, 0, str, 0, new HashMap<Character, String>());
 4     }
 5     
 6     private boolean helper(String pattern, int startP, String str, int startS, Map<Character, String> map) {
 7         if (startP == pattern.length() && startS == str.length()) {
 8             return true;
 9         } else if (startP == pattern.length()) {
10  
11             }
12             if (match.equals(str.substring(startS, endS))) {
13                 return helper(pattern, startP + 1, str, endS, map);
14             } else {
15                 return false;
16             }
17         } else {
18             // If map does not have existing key
19             // Traverse, brute force
20             
21             for (int i = startS + 1; i <= str.length(); i++) {
22                 String candidate = str.substring(startS, i);
23                 if (map.containsValue(candidate)) {
24                     continue;
25                 }
26                 map.put(key, candidate);
27                 if (helper(pattern, startP + 1, str, i, map)) {
28                     return true;
29                 }
30                 map.remove(key);
31             }
32         }
33         return false;
34     }
35 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4946364.html