Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6.  
  7. public class Solution {
  8.  
  9. static class Node {
  10. HashMap<Character, Node> children;
  11. boolean isCompleteWord;
  12. char value;
  13. int prefixCount;
  14.  
  15. public Node() {
  16. children = new HashMap<>();
  17. isCompleteWord = false;
  18. prefixCount = 0;
  19. }
  20. }
  21.  
  22. static void addWord(Node root, String word, int index, int length) {
  23. if (index == length) {
  24. root.isCompleteWord = true;
  25. root.prefixCount++;
  26. return;
  27. }
  28. else if(!root.children.containsKey(word.charAt(index))) {
  29. Node temp = new Node();
  30. temp.value = word.charAt(index);
  31. root.children.put(word.charAt(index), temp);
  32. }
  33.  
  34. root.prefixCount++;
  35. addWord(root.children.get(word.charAt(index)), word, index+1, length);
  36. }
  37.  
  38. static int findPrefixOccurrances(Node root, String word, int index, int length) {
  39. int count = 0;
  40. if (index < length && root.children.containsKey(word.charAt(index))) {
  41. count = findPrefixOccurrances(root.children.get(word.charAt(index)), word, index+1, length);
  42. } else if (index == length && word.charAt(index-1) == root.value){
  43. count = root.prefixCount;
  44. }
  45.  
  46. return count;
  47. }
  48.  
  49. public static void main(String[] args) {
  50.  
  51. Node root = new Node();
  52.  
  53. Scanner in = new Scanner(System.in);
  54. int n = in.nextInt();
  55. for(int a0 = 0; a0 < n; a0++){
  56. String op = in.next();
  57. String contact = in.next();
  58. // add to trie
  59. if (op.equals("add")) {
  60. addWord(root, contact, 0, contact.length());
  61. } else if (op.equals("find")) { // find occurrances
  62. int count = findPrefixOccurrances(root, contact, 0, contact.length());
  63. System.out.println(count);
  64. }
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement