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.

Note: You may assume the string contain only lowercase letters.

Python

 
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        a = dict()
        index = 0
        while index < len(s):
            if not isinstance(a.get(s[index], False), bool):
                a[s[index]] = -2
            else:
                a[s[index]] = index
            index += 1
        result = -1
        for key, value in a.items():
            if value != -2:
                if result != -1:
                    result = min(result, value)
                else:
                    result = value
        return result

发表评论