Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. //Dictionary implemented using a Trie Tree.
  2. public class Dictionary {
  3. private HashMap<Character,Node> roots = new HashMap<Character,Node>();
  4.  
  5. /**
  6. * Search through the dictionary for a word.
  7. * @param string The word to search for.
  8. * @return Whether or not the word exists in the dictionary.
  9. */
  10. public boolean search(String string) {
  11. if (roots.containsKey(string.charAt(0))) {
  12. if (string.length()==1 && roots.get(string.charAt(0)).endOfWord) {
  13. return true;
  14. }
  15. return searchFor(string.substring(1),roots.get(string.charAt(0)));
  16. }
  17.  
  18. return false;
  19. }
  20.  
  21. /**
  22. * Insert a word into the dictionary.
  23. * @param string The word to insert.
  24. */
  25. public void insert(String string) {
  26. if (!roots.containsKey(string.charAt(0))) {
  27. roots.put(string.charAt(0), new Node());
  28. }
  29.  
  30. insertWord(string.substring(1),roots.get(string.charAt(0)));
  31. }
  32.  
  33. //Recursive method that inserts a new word into the trie tree.
  34. private void insertWord(String string, Node node) {
  35. final Node nextChild;
  36. if (node.children.containsKey(string.charAt(0))) {
  37. nextChild = node.children.get(string.charAt(0));
  38. } else {
  39. nextChild = new Node();
  40. node.children.put(string.charAt(0), nextChild);
  41. }
  42.  
  43. if (string.length() == 1) {
  44. nextChild.endOfWord = true;
  45. return;
  46. }
  47.  
  48. insertWord(string.substring(1),nextChild);
  49. }
  50.  
  51.  
  52. //Recursive method that searches through the Trie Tree to find the value.
  53. private boolean searchFor(String string, Node node) {
  54. if (string.length()==0) {
  55. return node.endOfWord;
  56. }
  57.  
  58. if (node.children.containsKey(string.charAt(0))) {
  59. return searchFor(string.substring(1),node.children.get(string.charAt(0)));
  60. }
  61.  
  62. return false;
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement