Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. class StreamChecker {
  2.  
  3. private Trie trie = new Trie();
  4. private LinkedList<Character> queries = new LinkedList<Character>();
  5.  
  6. public StreamChecker(String[] words) {
  7.  
  8. for(String word : words) {
  9. char[] reverse = new char[word.length()];
  10. for (int i = word.length() - 1; i >= 0; i--) {
  11. reverse[word.length() - i - 1] = word.charAt(i);
  12. }
  13. trie.insert(new String(reverse), 0);
  14. }
  15. }
  16.  
  17. public boolean query(char letter) {
  18. queries.add(letter);
  19. return queryInternal(this.trie, queries.size() - 1);
  20. }
  21.  
  22. public boolean queryInternal(Trie t, Integer index) {
  23. if (index < 0) {
  24. return false;
  25. }
  26.  
  27. Trie current = t.getTrie(queries.get(index));
  28. if (current == null) {
  29. return false;
  30. }
  31.  
  32. if (current.completesWord) {
  33. return true;
  34. }
  35.  
  36. return queryInternal(current, --index);
  37. }
  38.  
  39. private class Trie {
  40.  
  41. private Map<Character, Trie> children;
  42. private boolean completesWord = false;
  43.  
  44. public Trie() {
  45. children = new HashMap<>();
  46. }
  47.  
  48. public void insert(String s, int index) {
  49. Trie child = this.children.computeIfAbsent(s.charAt(index), (x) -> new Trie());
  50. if (s.length() == index + 1) {
  51. child.completesWord = true;
  52. return;
  53. }
  54.  
  55. child.insert(s, ++index);
  56. }
  57.  
  58. public Trie getTrie(Character c) {
  59. return this.children.get(c);
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement