-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordPatternII291.java
More file actions
50 lines (44 loc) · 1.5 KB
/
Copy pathWordPatternII291.java
File metadata and controls
50 lines (44 loc) · 1.5 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
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.HashMap;
import java.util.HashSet;
public class WordPatternII291 {
public static boolean wordPatternMatch(String pattern, String str) {
HashMap<Character, String> map = new HashMap<>();
HashSet<String> set = new HashSet<>();
return isMatch(pattern, str, 0, 0, map, set);
}
public static boolean isMatch(String pattern, String str, int p, int s, HashMap<Character, String> map, HashSet<String> set) {
if (p == pattern.length() && s == str.length()) {
return true;
}
else if (p == pattern.length() || s == str.length()) {
return false;
}
char c = pattern.charAt(p);
// if "c" has appeared
if (map.containsKey(c)) {
String temp = map.get(c);
if (!str.startsWith(temp, s)) {
return false;
}
else {
return isMatch(pattern, str, p + 1, s + temp.length(), map, set);
}
}
else {
for (int i = s; i < str.length(); i++) {
String t = str.substring(s, i + 1);
//reduce duplication
if (!set.contains(t)) {
map.put(c, t);
set.add(t);
if (isMatch(pattern, str, p + 1, i + 1, map, set)) {
return true;
}
map.remove(c);
set.remove(t);
}
}
}
return false;
}
}