Dictionary Tree Search lintcode topic Add and Search Word

Source: Internet
Author: User
Tags lintcode

  1. Public class Worddictionary {
  2. private Trienode root = new Trienode ();
  3. public void Addword (String word) {
  4. Map<character, trienode> children = Root.children;
  5. For (int i=0; I<word.length (); i++) {
  6. char c = word.charat (i);
  7. Trienode T;
  8. if (Children.containskey (c)) {
  9. t = Children.get (c);
  10. } Else {
  11. t = new Trienode (c);
  12. Children.put (c, t);
  13. }
  14. children = T.children;
  15. if (i==word.length ()-1) t.leaf=true;
  16. }
  17. }
  18. Public Boolean search (String word) {
  19. return Searchnode (word, root);
  20. }
  21. Public Boolean searchnode (String Word, Trienode tn) {
  22. if (tn==null) return false;
  23. if (word.length () = = 0) return tn.leaf;
  24. Map<character, trienode> children = Tn.children;
  25. Trienode t = null;
  26. char c = Word.charat (0);
  27. if (c=='. ') {  
  28. For (Char key:children.keySet ()) {
  29. if (Searchnode (word.substring (1), Children.get (key)) return true;
  30. }
  31. return false;
  32. } Else if (!children.containskey (c)) {
  33. return false;
  34. } Else {
  35. t = Children.get (c);
  36. return Searchnode (word.substring (1), T);
  37. }
  38. }
  39. }
  40. Class Trienode {
  41. //Initialize your data structure here.
  42. Char C;
  43. Boolean leaf;
  44. Hashmap<character, trienode> children = New Hashmap<character, trienode> ();
  45. Public Trienode (char c) {
  46. this.c = c;
  47. }
  48. Public Trienode () {};
  49. }

Dictionary Tree Search lintcode topic Add and Search Word

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.