Thursday, May 5, 2022

Implement the Trie













package pep.Day79;

import java.io.*;
import java.util.*;

public class Implement_Trie {

public static class Trie {

class Node {
Node children[];
boolean isEnding;

Node() {
children = new Node[26];
}
}

/**
* Initialize your data structure here.
*/
Node root;

public Trie() {
root = new Node();
}

/**
* Inserts a word into the trie.
*/
public void insert(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
// agr current ki children ki index pr null hai toh
// new node bna denge
if (curr.children[word.charAt(i) - 'a'] == null)
curr.children[word.charAt(i) - 'a'] = new Node();
// current ko update kr denge
curr = curr.children[word.charAt(i) - 'a'];
}
// jab hum yha pr aa gae to word tree me add ho gya aur hum end pr aa gae
curr.isEnding = true;
}

/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
// agr current ki children ki index pr null hai toh
// word nhi mila
if (curr.children[word.charAt(i) - 'a'] == null)
return false;
// current ko update kr denge
curr = curr.children[word.charAt(i) - 'a'];
}
// jab hum yha pr aa gae to word tree me mil gya
return curr.isEnding;
}

/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
Node curr = root;
for (int i = 0; i < prefix.length(); i++) {
// agr current ki children ki index pr null hai toh
// humara prefix hai hi nhi
if (curr.children[prefix.charAt(i) - 'a'] == null)
return false;
// current ko update kr denge
curr = curr.children[prefix.charAt(i) - 'a'];
}
// jab hum yha pr aa gae to mujhe mera prefix mil gya
return true;
}
}

public static void main(String[] args) throws Exception {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

Trie obj = new Trie();

while (read.ready()) {
String inp[] = read.readLine().split(" ");

if (inp[0].equals("insert")) {
obj.insert(inp[1]);
} else if (inp[0].equals("search")) {
System.out.println(obj.search(inp[1]));
} else if (inp[0].equals("startsWith")) {
System.out.println(obj.startsWith(inp[1]));
}
}

}

}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...