Advertisement
Guest User

Untitled

a guest
Jul 18th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.20 KB | None | 0 0
  1. using System.CodeDom.Compiler;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Runtime.Serialization;
  11. using System.Text.RegularExpressions;
  12. using System.Text;
  13. using System;
  14.  
  15. class Solution {
  16.  
  17. public class Node
  18. {
  19. public char Value {get;private set;}
  20. IDictionary<char, Node> _children = new Dictionary<char, Node>();
  21.  
  22. public Node(char c)
  23. {
  24. Value = c;
  25. }
  26.  
  27. public bool HasChild(char c)
  28. {
  29. return _children.ContainsKey(c);
  30. }
  31.  
  32. public Node GetChild(char c)
  33. {
  34. return _children[c];
  35. }
  36.  
  37. public void AddChild(char c)
  38. {
  39. if(!_children.ContainsKey(c))
  40. {
  41. _children.Add(c, new Node(c));
  42. }
  43. }
  44.  
  45. public IEnumerable<Node> GetChildren()
  46. {
  47. return _children.Values;
  48. }
  49. }
  50.  
  51. public class AddressBook
  52. {
  53. private Node _head = new Node('*');
  54.  
  55. public void Add(string contact)
  56. {
  57. var currentNode = _head;
  58.  
  59. foreach(var c in contact)
  60. {
  61. currentNode.AddChild(c);
  62. currentNode = currentNode.GetChild(c);
  63. }
  64. currentNode.AddChild('*');
  65. }
  66.  
  67. public int GetContactsStartingWith(string prefix)
  68. {
  69. var currentNode = _head;
  70.  
  71. foreach(var c in prefix)
  72. {
  73. if(currentNode.HasChild(c))
  74. {
  75. currentNode = currentNode.GetChild(c);
  76. }
  77. else
  78. {
  79. return 0;
  80. }
  81. }
  82.  
  83. var stack = new Stack<Node>();
  84. stack.Push(currentNode);
  85. var contactsCount = 0;
  86. while(stack.Count > 0)
  87. {
  88. var currentSuffixNode = stack.Pop();
  89. if(currentSuffixNode.HasChild('*'))
  90. {
  91. contactsCount++;
  92. }
  93. foreach(var node in currentSuffixNode.GetChildren())
  94. {
  95. stack.Push(node);
  96. }
  97. }
  98.  
  99. return contactsCount;
  100. }
  101. }
  102.  
  103.  
  104. static void Main(string[] args) {
  105. int n = Convert.ToInt32(Console.ReadLine());
  106. var trie = new AddressBook();
  107. for (int nItr = 0; nItr < n; nItr++) {
  108. string[] opContact = Console.ReadLine().Split(' ');
  109.  
  110. string op = opContact[0];
  111.  
  112. string contact = opContact[1];
  113.  
  114. switch(op)
  115. {
  116. case "add":
  117. trie.Add(contact);
  118. break;
  119. case "find":
  120. Console.WriteLine(trie.GetContactsStartingWith(contact));
  121. break;
  122. }
  123. }
  124. }
  125. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement