Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import java.math.*;
- import java.util.regex.*;
- public class Solution {
- static class Node {
- HashMap<Character, Node> children;
- boolean isCompleteWord;
- char value;
- int prefixCount;
- public Node() {
- children = new HashMap<>();
- isCompleteWord = false;
- prefixCount = 0;
- }
- }
- static void addWord(Node root, String word, int index, int length) {
- if (index == length) {
- root.isCompleteWord = true;
- root.prefixCount++;
- return;
- }
- else if(!root.children.containsKey(word.charAt(index))) {
- Node temp = new Node();
- temp.value = word.charAt(index);
- root.children.put(word.charAt(index), temp);
- }
- root.prefixCount++;
- addWord(root.children.get(word.charAt(index)), word, index+1, length);
- }
- static int findPrefixOccurrances(Node root, String word, int index, int length) {
- int count = 0;
- if (index < length && root.children.containsKey(word.charAt(index))) {
- count = findPrefixOccurrances(root.children.get(word.charAt(index)), word, index+1, length);
- } else if (index == length && word.charAt(index-1) == root.value){
- count = root.prefixCount;
- }
- return count;
- }
- public static void main(String[] args) {
- Node root = new Node();
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- for(int a0 = 0; a0 < n; a0++){
- String op = in.next();
- String contact = in.next();
- // add to trie
- if (op.equals("add")) {
- addWord(root, contact, 0, contact.length());
- } else if (op.equals("find")) { // find occurrances
- int count = findPrefixOccurrances(root, contact, 0, contact.length());
- System.out.println(count);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement