What is the quickest way to find the first character which only appears once in a 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.
"": 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! ")
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With