Tuesday 15 April 2014

Time complexity of this unique string algorithm -


I am preparing for an interview and have come across a question where you can find all the unique characters in the string Let's try.

I have come up with an algorithm.

  The public static boolean is the unique chars (string str) {char [] charArray = str.toCharArray (); Maps & lt; Character, integer & gt; CharCounter = New TreeMap & lt; Character, Integer & gt; (); (Char i: charArray) {if (charCounter.containsKey (i)) returns incorrectly; Other charCounter.put (I, 1); } Back true; }  

I'm looking for a loop, so it's at least O (n). I believe that lookup in Hashp is also O (N). So does it make my algorithm o (n ^ 2)?

And if it is O (n ^ 2), then how is it better to loop than nested, where I array the rest of each character? It will also be O (N ^ 2) thanks

has it in ' S and. With this, the time cost of your algorithm is O (n log n). Since you do not need the values ​​in your map, you can use a set, eg. HashSet or TreeSet instead

It would be better to compare each string with the remaining string if you do not want to allocate the O (σ) memory (i.e. the size of the alphabet) match.


No comments:

Post a Comment