Advertisement
Guest User

Untitled

a guest
May 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. Given some dictionary list of words ("foo", "bar", "waz"), implement two functions:
  2. setupDictionary();
  3. -> This can take reasonable time to execute- it should populate and optionally preprocess the dictionary
  4.  
  5. isMember(word);
  6. -> This needs to be fast. Return true if the given word is in the dictionary.
  7.  
  8. Examples:
  9.  
  10. isMember("foo"); // true
  11. isMember("f.o"); // true
  12. isMember("w.."); // true
  13. isMember(".."); // false
  14. isMember("blah"); // false
  15.  
  16. ==
  17.  
  18. Setup O(1)
  19. Set<- add
  20.  
  21. isMember O(n)
  22.  
  23. Setup O(n)
  24. root->{f}->{o}->{o}-true
  25.  
  26. isMember O(len(n)) + O(1) + O(1) "foo".length
  27. O(1) + O(map.size()) + O(map.size()) = O(max(map.size()) -> O(n)
  28.  
  29.  
  30. class TrieNode<T>{
  31. Map<T, TrieNode> children;
  32. boolean end_of_list;
  33. }
  34. TrieNode<Character> root = new TrieNode();
  35. public void setupDictionary(String input) throws Exception{
  36. if(input==null){
  37. throw new Exception("input is null");
  38. }
  39. TrieNode curr = root;
  40. for(int i=0; i<input.length(); i++){
  41. if(curr.children.containsKey(input.charAt(i)){
  42. curr = curr.children.get(input.charAt(i));
  43. }else{
  44. TrieNode<Character> newNode = new TrieNode();
  45. curr.children.put(input.charAt(i), newNode);
  46. curr = newNode;
  47. }
  48. }
  49. curr.end_of_list = true;
  50. }
  51. public boolean isMember(String input, TrieNode curr){
  52. for(int i=0; i<input.length(); i++){
  53. if(input.charAt(i) != "."){
  54. if(!curr.children.containsKey(input.charAt(i)){
  55. return false;
  56. }else{
  57. curr = curr.children.get(input.charAt(i));
  58. }
  59. }else{
  60. for(Character c:curr.children.keySet()){
  61. isMember(input.substring(i+1),curr.children.get(c));
  62. }
  63. }
  64. }
  65. return true;
  66. }
  67.  
  68. what: insert "foo"
  69. output: root{f}->newNode{o}->newNode{o}->newNode{end_of_list=true}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement