3 ms·
I assume you mean first non-repeated character. Anyways heres a possible performance improvement for a very long string: Assume the string is stored as a link
by spaghetti 15y ago
I assume you mean first non-repeated character. Anyways heres a possible performance improvement for a very long string:
Assume the string is stored as a linked-list (so removing characters from the middle of the string is cheap). Then remove duplicates from the string during the initial traversal (keep track of unique characters that were removed as duplicates in a hashtable). After this single traversal the character in the head node of the remaining linked-list will be the first non-repeated character in the original string.
Note the string must be stored in the linked-list initially... if we're responsible for moving the string from a theoretical array w/ billions of elements then we have to traverse the string twice just like the original algorithm and nothing is gained.
Please clarify the "usually in the middle" part of your question. In this case do we always have to return the first non-repeated character? Or can we just be close?
- kenjackson 15y agoYes, first non-repeated, my bad. The usually in the middle is meant to say that typically the first character returned is position ~s.length/2. The linked list idea is good. I wasn't thinking of that at all.
- spaghetti 15y agoOne mistake I made: after the first traversal over the linked-list the character in the head node of the remaining list is not necessarily the first non-repeated character. Consider the string "aba" for example. However the second traversal will be over a shorter list... So this approach might get you somewhere :-)