-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPrefixAndSuffixSearch.java
85 lines (75 loc) · 2.42 KB
/
PrefixAndSuffixSearch.java
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
/*https://leetcode.com/problems/prefix-and-suffix-search/*/
//hashing
class WordFilter
{
HashMap<String, TreeSet<Integer>> prefMap = new HashMap<>();
HashMap<String, TreeSet<Integer>> suffMap = new HashMap<>();
public WordFilter(String[] words)
{
for (int i = 0; i < words.length; i++)
{
for (int j = 0; j < words[i].length(); j++)
{
String s1 = words[i].substring(0, j+1);
String s2 = words[i].substring(j, words[i].length());
if (!prefMap.containsKey(s1))
prefMap.put(s1, new TreeSet<>(Collections.reverseOrder()));
if (!suffMap.containsKey(s2))
suffMap.put(s2, new TreeSet<>(Collections.reverseOrder()));
prefMap.get(s1).add(i);
suffMap.get(s2).add(i);
}
}
}
public int f(String pref, String suff)
{
if (prefMap.containsKey(pref) == false || suffMap.containsKey(suff) == false)
return -1;
TreeSet<Integer> p = prefMap.get(pref);
TreeSet<Integer> s = suffMap.get(suff);
for (Integer val : p)
if (s.contains(val))
return val;
return -1;
}
}
//trie
class WordFilter {
TrieNode root;
String[] words;
public WordFilter(String[] words) {
root = new TrieNode();
TrieNode node = root;
for (int i = 0; i < words.length; i++) {
for (char ch : words[i].toCharArray()) {
if (root.child[ch - 'a'] == null) {
root.child[ch - 'a'] = new TrieNode();
}
root.child[ch - 'a'].indexList.add(i);
root = root.child[ch - 'a'];
}
root = node;
}
this.words = words;
}
public int f(String prefix, String suffix) {
TrieNode node = root;
for (char ch : prefix.toCharArray()) {
node = node.child[ch - 'a'];
if (node == null) {
return -1;
}
}
List<Integer> list = node.indexList;
for (int i = list.size() - 1; i >= 0; i--) {
if (words[list.get(i)].endsWith(suffix)) {
return list.get(i);
}
}
return -1;
}
private static class TrieNode {
TrieNode[] child = new TrieNode[26];
List<Integer> indexList = new ArrayList<>();
}
}