-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWordPattern.java
More file actions
91 lines (78 loc) · 2.26 KB
/
WordPattern.java
File metadata and controls
91 lines (78 loc) · 2.26 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package Dropbox;
import java.util.*;
/**
* Created by cicean on 9/26/2018.
*/
public class WordPattern {
public boolean wordPattern(String pattern, String teststr) {
// write your code here
if (pattern == null || teststr == null) {
return false;
}
Map<Character, String> map = new HashMap<>();
String[] strs = teststr.split(" ");
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (!map.containsKey(c)) {
if (map.containsValue(strs[i])) {
return false;
}
map.put(c, strs[i]);
}
else {
if (!strs[i].equals(map.get(c))) {
return false;
}
}
}
return true;
}
/**
* no space of the words
* @param pattern
* @param str
* @return
*/
public boolean wordPatternMatch(String pattern, String str) {
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
return match(pattern, str, map, set);
}
private boolean match(String pattern,
String str,
Map<Character, String> map,
Set<String> set) {
if (pattern.length() == 0) {
return str.length() == 0;
}
Character c = pattern.charAt(0);
if (map.containsKey(c)) {
if (!str.startsWith(map.get(c))) {
return false;
}
return match(
pattern.substring(1),
str.substring(map.get(c).length()),
map,
set
);
}
for (int i = 0; i < str.length(); i++) {
String word = str.substring(0, i + 1);
if (set.contains(word)) {
continue;
}
map.put(c, word);
set.add(word);
if (match(pattern.substring(1),
str.substring(i + 1),
map,
set)) {
return true;
}
set.remove(word);
map.remove(c);
}
return false;
}
}