Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.CodeDom.Compiler;
- using System.Collections.Generic;
- using System.Collections;
- using System.ComponentModel;
- using System.Diagnostics.CodeAnalysis;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Text.RegularExpressions;
- using System.Text;
- using System;
- class Solution {
- public class Node
- {
- public char Value {get;private set;}
- IDictionary<char, Node> _children = new Dictionary<char, Node>();
- public Node(char c)
- {
- Value = c;
- }
- public bool HasChild(char c)
- {
- return _children.ContainsKey(c);
- }
- public Node GetChild(char c)
- {
- return _children[c];
- }
- public void AddChild(char c)
- {
- if(!_children.ContainsKey(c))
- {
- _children.Add(c, new Node(c));
- }
- }
- public IEnumerable<Node> GetChildren()
- {
- return _children.Values;
- }
- }
- public class AddressBook
- {
- private Node _head = new Node('*');
- public void Add(string contact)
- {
- var currentNode = _head;
- foreach(var c in contact)
- {
- currentNode.AddChild(c);
- currentNode = currentNode.GetChild(c);
- }
- currentNode.AddChild('*');
- }
- public int GetContactsStartingWith(string prefix)
- {
- var currentNode = _head;
- foreach(var c in prefix)
- {
- if(currentNode.HasChild(c))
- {
- currentNode = currentNode.GetChild(c);
- }
- else
- {
- return 0;
- }
- }
- var stack = new Stack<Node>();
- stack.Push(currentNode);
- var contactsCount = 0;
- while(stack.Count > 0)
- {
- var currentSuffixNode = stack.Pop();
- if(currentSuffixNode.HasChild('*'))
- {
- contactsCount++;
- }
- foreach(var node in currentSuffixNode.GetChildren())
- {
- stack.Push(node);
- }
- }
- return contactsCount;
- }
- }
- static void Main(string[] args) {
- int n = Convert.ToInt32(Console.ReadLine());
- var trie = new AddressBook();
- for (int nItr = 0; nItr < n; nItr++) {
- string[] opContact = Console.ReadLine().Split(' ');
- string op = opContact[0];
- string contact = opContact[1];
- switch(op)
- {
- case "add":
- trie.Add(contact);
- break;
- case "find":
- Console.WriteLine(trie.GetContactsStartingWith(contact));
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement