Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Unique Character in a String

Tags:

python

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

first_unique('leetcode')  # 0
first_unique('loveleetcode')  # 2

I came up with the following solution. How can I make it more efficient for very long input strings?

def first_unique(self, s):
    if s == '':
        return -1

    for item in s:
        if s.count(item) == 1:
            return s.index(item)
            break

    return -1
like image 751
alex.l Avatar asked Oct 27 '25 12:10

alex.l


1 Answers

My solution uses Counter form the collections module.

from collections import Counter
def first_unique(s):
    c = Counter(s)
    for i in range(len(s)):
        if c[s[i]] == 1:
            return i
    return -1
like image 173
Patrick Haugh Avatar answered Oct 29 '25 01:10

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!