We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is a solution that actually uses the notion of "Sparse Arrays" (if you used Maps or LINQ you really missed the point of the exercise):
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;classSolution{publicclassNode{privateintcount=0;privateintdepth;privateNode[]subnodes=null;privateNode[]Subnodes{get{if(subnodes==null){subnodes=newNode[52];// support A-Z a-z}returnsubnodes;}}publicNode():this(0){}privateNode(intdepth){this.depth=depth;}publicintAdd(stringstr){Nodecurrent=this;for(inti=0;i<str.Length;i++){intindex=CharNodeIndex(str[i]);if(current.Subnodes[index]==null){current.Subnodes[index]=newNode(depth+1);}current=current.Subnodes[index];}current.count++;returncurrent.count;}publicintCountOf(stringstr){Nodecurrent=this;for(inti=0;i<str.Length;i++){intindex=CharNodeIndex(str[i]);if(current.Subnodes[index]==null){return0;}current=current.Subnodes[index];}returncurrent.count;}privateintCharNodeIndex(charc){intindex=0;if(c>='A'&&c<='Z'){index=c-'A';}elseif(c>='a'&&c<='z'){index=c-'a'+26;}else{thrownewArgumentException("String may only contain the letters A-Z and a-z");}returnindex;}}staticvoidMain(String[]args){Nodenode=newNode();intstrCount=int.Parse(Console.In.ReadLine());for(inti=0;i<strCount;i++){stringstr=Console.In.ReadLine();node.Add(str);}intqueryCount=int.Parse(Console.In.ReadLine());for(inti=0;i<queryCount;i++){stringstr=Console.In.ReadLine();Console.Out.WriteLine(node.CountOf(str));}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sparse Arrays
You are viewing a single comment's thread. Return to all comments →
Here is a solution that actually uses the notion of "Sparse Arrays" (if you used Maps or LINQ you really missed the point of the exercise):