Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first un-repeated character in a string

Tags:

What is the quickest way to find the first character which only appears once in a string?

like image 919
Thunderhashy Avatar asked Feb 18 '10 00:02

Thunderhashy


People also ask

How do you find the first non repeated character in the string?

Using the indexOf() and lastIndexOf() method, we can find the first non-repeating character in a string in Java. The method indexOf() returns the position of the first occurrence of a given character in a string whereas method lastIndexOf() returns the position of the last occurrence of a given character in a string.

How do I find the first non repeated character of a string in Python?

"": slen0 = len(myStr) ch = myStr[0] myStr = myStr. replace(ch, "") slen1 = len(myStr) if slen1 == slen0-1: print ("First non-repeating character = ",ch) break; else: print ("No Unique Character Found! ")

How do you find the first unique characters in a string?

To find the index of the first unique character present in the given string, we can use the hashmap. The idea is to go through all the characters of the string and create a hashmap with Key as the character and Value as its occurrences.


1 Answers

It has to be at least O(n) because you don't know if a character will be repeated until you've read all characters.

So you can iterate over the characters and append each character to a list the first time you see it, and separately keep a count of how many times you've seen it (in fact the only values that matter for the count is "0", "1" or "more than 1").

When you reach the end of the string you just have to find the first character in the list that has a count of exactly one.


Example code in Python:

def first_non_repeated_character(s):     counts = defaultdict(int)     l = []     for c in s:         counts[c] += 1         if counts[c] == 1:             l.append(c)      for c in l:         if counts[c] == 1:             return c      return None 

This runs in O(n).

like image 130
Mark Byers Avatar answered Oct 17 '22 05:10

Mark Byers