Advertisement
Guest User

Untitled

a guest
Jul 1st, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public class WordDictionary {
  2. private class DicNode {
  3. boolean contains;
  4. Map<Character, DicNode> children;
  5.  
  6. DicNode() {
  7. contains = false;
  8. children = new HashMap<>();
  9. }
  10. }
  11.  
  12. private DicNode root;
  13.  
  14. public WordDictionary() {
  15. root = new DicNode();
  16. }
  17.  
  18. // Adds a word into the data structure.
  19. public void addWord(String word) {
  20. if (word == null || word.length() == 0)
  21. return;
  22. DicNode n = root;
  23. for (int i = 0; i < word.length(); i++) {
  24. char c = word.charAt(i);
  25. if (!n.children.containsKey(c)) {
  26. n.children.put(c, new DicNode());
  27. }
  28. n = n.children.get(c);
  29. }
  30. n.contains = true;
  31. }
  32.  
  33. // Returns if the word is in the data structure. A word could
  34. // contain the dot character '.' to represent any one letter.
  35. public boolean search(String word) {
  36. return search(word, root);
  37. }
  38.  
  39. private boolean search(String word, DicNode root) {
  40. if ("".equals(word))
  41. return root.contains;
  42. char first = word.charAt(0);
  43. if ( first == '.' ) {
  44. for (DicNode n: root.children.values()) {
  45. if (search(word.substring(1), n))
  46. return true;
  47. }
  48. return false;
  49. } else {
  50. // first != '.'
  51. return root.children.containsKey(first) && search(word.substring(1), root.children.get(first));
  52. }
  53. }
  54. }
  55.  
  56. // Your WordDictionary object will be instantiated and called as such:
  57. // WordDictionary wordDictionary = new WordDictionary();
  58. // wordDictionary.addWord("word");
  59. // wordDictionary.search("pattern");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement