You are viewing a single comment's thread. Return to all comments →
c= curr.children.size(); if(curr.endofwrd) c=c+1; return c;
is wrong.
proper solution:
import java.util.Scanner; class Node { char c; Node[] children = new Node[26]; boolean isLeafNode; int count; Node(char c, boolean isLeafNode, int count) { this.c = c; this.isLeafNode = isLeafNode; this.count = count; } } public class Solution { static Node root; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); root = new Node(' ', false, 0); for (int tc = 1; tc <= T; tc++) { String operation = sc.next(); String input = sc.next(); if (operation.equals("add")) { insert(input); } else { System.out.println(find(input)); } } } public static void insert(String word) { Node current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); Node node = current.children[ch - 'a']; if (node == null) { current.children[ch - 'a'] = new Node(ch, false, 1); } else { current.children[ch - 'a'].count = current.children[ch - 'a'].count + 1; } current = current.children[ch - 'a']; } current.isLeafNode = true; } public static int find(String prefix) { Node curr = root; int c = 0; for (int i = 0; i < prefix.length(); i++) { Character ch = prefix.charAt(i); if (!containsKey(curr, ch)) { return 0; } else { curr = curr.children[ch - 'a']; } } return curr.count; } private static boolean containsKey(Node curr, char ch) { for (int i = 0; i < 26; i++) { if (curr.children[i] != null) if (curr.children[i].c == ch) { return true; } } return false; } private static int getChidrenSize(Node curr) { int count = 0; for (int i = 0; i < 26; i++) { if (curr.children[i] != null) { count++; } } return count; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Contacts
You are viewing a single comment's thread. Return to all comments →
c= curr.children.size(); if(curr.endofwrd) c=c+1; return c;
is wrong.
proper solution: