Python O(N) solution using Counter

  • 0
    from collections import Counter
    class Solution(object):
        def firstUniqChar(self, s):
            # Make the counter object
        	count = Counter(s)
            # Create a set within chars who only appears once
        	candidates = {k for (k,v) in count.iteritems() if v == 1}
            # Check the chars in the string in order
        	for i in xrange(len(s)):
        		if s[i] in candidates:
        			return i
        	return -1

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.