-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek 5 291. Word Pattern II
More file actions
37 lines (32 loc) · 1.29 KB
/
week 5 291. Word Pattern II
File metadata and controls
37 lines (32 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public boolean wordPatternMatch(String pattern, String str) {
HashMap map = new HashMap();
return dfs(pattern, 0, str, 0, map);
}
private boolean dfs(String pattern, int i, String str, int j, HashMap map){
if(i == pattern.length() && j == str.length()){
return true;
}
if(i == pattern.length() || j == str.length()){
return false;
}
char c = pattern.charAt(i);
for(int k = j; k < str.length(); k++){
if(map.get(c) == map.get(str.substring(j, k+1))){
Integer val = (Integer)map.get(c);
if(val == null){
map.put(pattern.charAt(i), i);
map.put(str.substring(j, k+1), i);
}
if(dfs(pattern, i+1, str, k+1, map)){//dfs
return true;
}
if(val == null){// backtracking
map.remove(pattern.charAt(i));
map.remove(str.substring(j, k+1));
}
}
}
return false;
}
}