- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathWordPatternII291.java
More file actions
Latest commit
58 lines (54 loc) · 1.95 KB
/
Copy pathWordPatternII291.java
File metadata and controls
58 lines (54 loc) · 1.95 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
51
52
53
54
55
56
57
58
/**
* 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.
*
* Example 1:
* Input: pattern = "abab", str = "redblueredblue"
* Output: true
*
* Example 2:
* Input: pattern = pattern = "aaaa", str = "asdasdasdasd"
* Output: true
*
* Example 3:
* Input: pattern = "aabb", str = "xyzabcxzyabc"
* Output: false
*
* Notes:
* You may assume both pattern and str contains only lowercase letters.
*/
publicclassWordPatternII291 {
publicbooleanwordPatternMatch(Stringpattern, Stringstr) {
if (pattern.length() == 0) returnstr.length() == 0;
if (str.length() == 0) returnfalse;
returnmatch(pattern, 0, str, 0, newString[26], newHashMap<>());
}
privatebooleanmatch(Stringpattern, inti, Stringstr, intj, String[] p2s, Map<String, Character> s2p) {
if (i == pattern.length()) returnj == str.length();
if (j == str.length()) returnfalse;
charp = pattern.charAt(i);
if (p2s[p-'a'] != null) {
Stringsub = p2s[p-'a'];
if (!str.startsWith(sub, j)) returnfalse;
if (match(pattern, i+1, str, j+sub.length(), p2s, s2p)) returntrue;
} else {
for (intk=j+1; k<=str.length(); k++) {
Stringsub = str.substring(j, k);
if (s2p.containsKey(sub)) {
charp0 = s2p.get(sub);
if (p0 != p) continue;
if (match(pattern, i+1, str, j+sub.length(), p2s, s2p)) returntrue;
} else {
p2s[p-'a'] = sub;
s2p.put(sub, p);
if (match(pattern, i+1, str, j+sub.length(), p2s, s2p)) returntrue;
p2s[p-'a'] = null;
s2p.remove(sub);
}
}
}
returnfalse;
}
}