-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDLB.java
More file actions
117 lines (96 loc) · 2.39 KB
/
DLB.java
File metadata and controls
117 lines (96 loc) · 2.39 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.util.*;
public class DLB implements DictionaryInterface
{
private Node root; //root node, holds no data
private Node currentNode; //private iterator
public class Node
{
private char value; //current char value
private Node peer = null; //peer nodes, left to right
private Node child = null; //next letter in word, goes down
private boolean isAWord = false; //is true if the current node is the end of a word
}
public DLB() //constructor
{
root = new Node();
}
public boolean add(String s)
{
currentNode = root;
int index = 0;
for(int i=0; i<s.length(); i++)
{
char currentChar = s.charAt(i);
if(currentNode.child != null ) //there is a current child node to the currentNode, go down 1 level
{
currentNode = currentNode.child;
}
else //there is no current child node, create one
{
Node temp = new Node();
temp.value = currentChar;
currentNode.child = temp;
currentNode = currentNode.child;
}
while(currentNode.value != currentChar) //gets to end of peer links or will end when currentNode.value == currentChar
{
if(currentNode.peer != null) //means that the line of peers is longer, make currentNode the next peer
{
currentNode = currentNode.peer;
}
else
{
Node temp = new Node();
temp.value = currentChar;
currentNode.peer = temp;
currentNode = currentNode.peer;
}
}
}
currentNode.isAWord = true;
return true;
}
public int search(StringBuilder s)
{
currentNode = root; //currentNode is now root
for(int i = 0; i < s.length(); i++ )
{
char currentChar = s.charAt(i); //gets current char
if(currentNode.child != null)
{
currentNode = currentNode.child;
}
else
{
return 0; //if cannot go to child while in the for loop then break to test cases
}
while(currentNode.value != currentChar) //go through all peers
{
if(currentNode.peer != null)
{
currentNode = currentNode.peer; //move to next peer
}
else
{
return 0; //if no more peers then the word is not in DLB
}
}
}
if(currentNode.child != null && currentNode.isAWord)
{
return 3; //s is both a prefix and a word
}
else if(currentNode.isAWord)
{
return 2; //s is a word
}
else if(currentNode.child != null)
{
return 1; //s is a prefix
}
else
{
return 0; //s is not a word
}
}
}