-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternSearchTrie.java
More file actions
75 lines (67 loc) · 1.44 KB
/
Copy pathPatternSearchTrie.java
File metadata and controls
75 lines (67 loc) · 1.44 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
package com.learn.tree;
import java.util.Map;
import java.util.Set;
public class PatternSearchTrie {
static Trie root;
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words = {"beb","black","amateur","zen","aman"};
PatternSearchTrie pt = new PatternSearchTrie();
for (String s: words)
{
pt.add(s);
}
pt.traverse(root.list);
System.out.println(pt.find("zena"));
}
public void traverse(Map<Character,Trie> list)
{
Set<Character> keys = list.keySet();
if(keys.isEmpty())
return;
for(Character key : keys)
{
System.out.println(key);
traverse(list.get(key).list);
}
}
public void add(String s)
{
if(root == null)
{
Trie newnode = new Trie((char)0);
root = newnode;
}
char[] str = s.toCharArray();
int length = str.length;
Trie currentnode = root;
for(int i=0;i<length;i++)
{
if(currentnode.list.containsKey(str[i]))
{
currentnode = currentnode.list.get(str[i]);
}
else
{
Trie newnode = new Trie(str[i]);
currentnode.list.put(str[i], newnode);
currentnode = newnode;
}
}
currentnode.word=true;
}
public boolean find(String str)
{
int length = str.length();
char[] array = str.toCharArray();
Trie currentnode = root;
for(int i=0;i<length;i++)
{
if(currentnode.list.containsKey(array[i]))
currentnode = currentnode.list.get(array[i]);
else
return false;
}
return true;
}
}