387. First Unique Character in a String

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

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Thoughts:

Count then find

Code (324ms)

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        f = {}

        for c in s:
            if c not in f.keys():
                f[c] = 1
            else:
                f[c] += 1

        for i in range(len(s)):
            c = s[i]
            if f[c] == 1:
                return i
        return -1
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        chars = 'abcdefghijklmnopqrstuvwxyz'
        index = [s.index(c) for c in chars if s.count(c) == 1]
        return min(index) if len(index) else -1

results matching ""

    No results matching ""