-
Notifications
You must be signed in to change notification settings - Fork 1
/
Trie.java
96 lines (76 loc) · 2.26 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
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.Arrays;
class Trie {
private TrieNode root;
private ArrayList<String> list;
private boolean flag[];
public Trie() {
root = new TrieNode();
list = new ArrayList<String>();
flag = new boolean[100];
}
private void init(){
Arrays.fill(flag, false);
list.clear();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char currentChar = word.charAt(i);
if (!node.containsKey(currentChar)) {
node.put(currentChar, new TrieNode());
}
node = node.get(currentChar);
}
node.setEnd();
}
private void searchMatch(TrieNode node, String word, String matchedWord) {
if(node.isEnd())
{
if(matchedWord.length() > 1)
list.add(matchedWord);
}
String matchThisFar = "";
for(int i = 0; i<word.length(); i++)
{
char currChar = word.charAt(i);
if(node.containsKey(currChar) && !flag[i])
{
TrieNode newNode = node.get(currChar);
matchThisFar = matchedWord + currChar;
flag[i] = true;
searchMatch(newNode, word, matchThisFar);
flag[i] = false;
}
}
}
public boolean search(String word) {
init();
String matchedWord = "";
searchMatch(root, word, matchedWord);
return true;
}
public void showSorted() throws IOException {
Collections.sort(list, new MyComparator());
Collections.reverse(list);
Set<String> newlist = new LinkedHashSet<>(list);
BufferedWriter fileout = null;
fileout = new BufferedWriter(new FileWriter("output.txt"));
for (Iterator<String> it = newlist.iterator(); it.hasNext(); ) {
String f = it.next();
System.out.println(f);
fileout.write(f);
fileout.newLine();
}
fileout.close();
}
}