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.

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

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        res = []
        for i in s:
            # print(i)
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] = 2
        # print(dic)
        for key,value in dic.items():
            if value==1:
                res.append(key)
        if len(res):
            return min(s.find(i) for i in res)
        else:
            return -1
posted @ 2018-10-18 11:23  bernieloveslife  阅读(93)  评论(0)    收藏  举报