Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import java.util.HashSet;
  2.  
  3. public class TrieImpl {
  4.  
  5. public TrieImpl() {
  6. root = null;
  7. }
  8.  
  9. private static int R = 33; // alphabet size
  10. private Node root;
  11.  
  12. private static class Node {
  13. private HashSet<Integer> val;
  14. private Node[] next = new Node[R];
  15. }
  16.  
  17. public HashSet<Integer> get(String key) {
  18. Node x = get(root, key, 0);
  19. if (x == null) return null;
  20. return (HashSet<Integer>) x.val;
  21. }
  22. private Node get(Node x, String key, int d) {
  23. if (x == null) return null;
  24. if (d == key.length()) return x;
  25. char c = key.charAt(d);
  26. return get(x.next[charIndex(c)], key, d+1);
  27. }
  28. public void put(String key, int val) {
  29. root = put(root, key, val, 0);
  30. }
  31. private Node put(Node x, String key, int val, int d) {
  32. if (x == null) x = new Node();
  33. if (d == key.length()) {
  34. if (null != x.val) { x.val.add(val); }
  35. else {
  36. x.val = new HashSet<Integer>();
  37. x.val.add(val);
  38. }
  39. return x;
  40. }
  41. char c = key.charAt(d);
  42. x.next[charIndex(c)] = put(x.next[charIndex(c)], key, val, d+1);
  43. return x;
  44. }
  45. private int charIndex(char c) {
  46. if(c >= 'а' && c <= 'е') return c - 'а';
  47. else if (c >= 'ж' && c <= 'я') return c - 'а' + 1;
  48. else if (c == 'ё') return 'ж' - 'а';
  49. return 0;
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement