-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathtrie.java
97 lines (76 loc) · 1.79 KB
/
trie.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
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.*;
class Trie{
static class trieNode{
trieNode[] child;
boolean end;
trieNode(){
child=new trieNode[26];
end=false;
for(int i=0;i<26;i++)
{
child[i]=null;
}
}
}
static trieNode root;
static void insert(String s){
int len=s.length();
trieNode crawl=root;
for(int i=0;i<len;i++){
int index=s.charAt(i)-'a';
if(crawl.child[index]==null)
crawl.child[index]=new trieNode();
crawl=crawl.child[index];
}
crawl.end=true;
}
static boolean search(String s){
trieNode crawl=root;
for(int i=0;i<s.length();i++){
int index=s.charAt(i)-'a';
if(crawl.child[index]!=null){
crawl=crawl.child[index];
}}
return crawl.end;
}
static boolean startswith(String s){
trieNode crawl=root;
for(int i=0;i<s.length();i++){
int index=s.charAt(i)-'a';
if(crawl.child[index]==null) return false;
crawl=crawl.child[index];
}
return true;
}
public static void printTrie(trieNode curr,List<Character> li){
if(curr==null) return;
if(curr.end==true){
System.out.println(li);
}
for(int i=0;i<26;i++){
if(curr.child[i]!=null){
li.add((char)(i+'a'));
printTrie(curr.child[i],li);
li.remove(li.size()-1);
}
}
}
public static void main(String[] args){
String s="these";
root=new trieNode();
insert(s);
insert("hepl");
insert("thr");
insert("th");
//int i=0;
/* while(root.end!=true){
System.out.print(s.charAt(i)+"--");
root=root.child[s.charAt(i)-'a'];
i++;
}*/
System.out.println(startswith("he"));
System.out.println(search("hthese"));
List<Character> li=new ArrayList<>();
printTrie(root,li);
}
}