From 4ed2aa3d21da745f92042a4395912ade63713c8d Mon Sep 17 00:00:00 2001 From: ShrutiSolani <68545365+ShrutiSolani@users.noreply.github.com> Date: Sat, 9 Oct 2021 21:52:43 +0530 Subject: [PATCH] Add files via upload --- Java/Trie.java | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Java/Trie.java diff --git a/Java/Trie.java b/Java/Trie.java new file mode 100644 index 00000000..15901a0d --- /dev/null +++ b/Java/Trie.java @@ -0,0 +1,78 @@ +import java.util.Scanner; +import java.util.Stack; + +class Node{ + boolean word_end; + Node[] children = new Node[26]; + + Node(){ + word_end = false; + for(int i = 0;i < 26;i++){ + children[i] = null; + } + } +} + +class Trie{ + private static Node root; + + static void insert(String str){ + Node current = root; + for(int i = 0;i < str.length();i++){ + char ch = str.charAt(i); + if(current.children[ch-'a'] == null){ + current.children[ch-'a'] = new Node(); + } + current = current.children[ch-'a']; + } + current.word_end = true; + System.out.println("String inserted"); + } + + static void search(String str){ + Node current = root; + for(int i = 0;i < str.length();i++){ + char ch = str.charAt(i); + if(current.children[ch-'a'] == null){ + System.out.println("Word does not exist"); + return; + } + else{ + current = current.children[ch-'a']; + } + } + if(current.word_end){ + System.out.println("Word found"); + } + else{ + System.out.println("Word does not exist"); + } + } + + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int choice = 0; + root = new Node(); + + while(choice != 3){ + System.out.println("Select one operation : 1) Insert\t2) Search\t3) Exit"); + choice = sc.nextInt(); + switch(choice){ + case 1: + System.out.print("Enter a string to insert - "); + String str = sc.next(); + insert(str); + break; + case 2: + System.out.print("Enter a string to search -"); + String st = sc.next(); + search(st); + break; + default: + break; + } + } + + } +}