Your task is to create a trie system that is hosted online with a global state that supports multiple concurrent clients and the following operations:
- Add keyword to trie
- Delete a keyword from trie
- Search for a keyword in trie [True/False]
- Return list of autocomplete suggestion based on an input prefix
- Display the trie
Node Class:
package com.stack.trie;
public class Node {
public Node[] links = new Node[26];
public int ctrEndWith;
public int ctrPrefix;
public boolean flag;
boolean containsKey(char ch)
{
return (links[ch-'a']!=null);
}
Node get(char ch)
{
return links[ch-'a'];
}
void put(char ch,Node node)
{
links[ch-'a']=node;
}
void increaseEnd()
{
ctrEndWith++;
}
void increasePrefix()
{
ctrPrefix++;
}
void deleteEnd()
{
ctrEndWith--;
}
void reducePrefix()
{
ctrPrefix--;
}
int getEnd()
{
return ctrEndWith;
}
int getPrefix()
{
return ctrPrefix;
}
void setEnd()
{
flag=true;
}
boolean isEnd()
{
return flag;
}
}
And Functions:
public class Trie1 {
public Node root = new Node();
public void add(String word) {
Node node = root;
int i;
for (i = 0; i < word.length(); i++) {
if (node.containsKey(word.charAt(i))) {
node.put(word.charAt(i), new Node());
}
node = node.get(word.charAt(i));
node.increasePrefix();
}
node.setEnd();
}
public boolean search(String word) {
Node node = root;
int i;
for (i = 0; i < word.length(); i++) {
if (!node.containsKey(word.charAt(i))) {
return false;
}
node = node.get(word.charAt(i));
}
return node.isEnd();
}
void delete(String word) {
Node node = root;
int i;
for (i = 0; i < word.length(); i++) {
if (node.containsKey(word.charAt(i))) {
node = node.get(word.charAt(i));
node.reducePrefix();
} else {
return;
}
}
node.deleteEnd();
}
void suggest() {
}
String display() {
return null;
}
public void mainMenu() {
Scanner sc = new Scanner(System.in);
int ch;
String str;
do {
System.out.println("\t\tTrie Menu");
System.out.println("\t\t1.Add");
System.out.println("\t\t2.Delete");
System.out.println("\t\t3.Search");
System.out.println("\t\t4.Return Suggestions");
System.out.println("\t\t5.Display Trie");
System.out.println("\t\t6.Exit");
System.out.print("\t\tPlease enter a choice.");
ch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Enter keyword to be added");
str = sc.nextLine();
add(str);
break;
case 2:
System.out.println("Enter keyword to be deleted");
str = sc.nextLine();
break;
case 3:
System.out.println("Please enter search term");
str = sc.nextLine();
search(str);
break;
case 4:
System.out.println("Please enter prefix");
str = sc.nextLine();
break;
case 5:
display();
break;
case 6:
System.out.println("Thank you!");
break;
default:
System.out.println("Invalid Input. Please try again.");
}
} while (ch != 6);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Trie1 obj = new Trie1();
obj.mainMenu();
}
}