My easy understantd python solution with dictionary function


  • 0
    Y

    I use dictionary to store each char and the occurrence time, after all, sort and return the first unique char.

        def firstUniqChar(self, s):
            """
            :type s: str
            :rtype: int
            """
            #The first condition is important
            #use the temp array for saving the non-repeating item in s
            #use res to save the index of non-repeating item in s
            dic={}
            for i in s:
                dic[i]=dic.get(i,0)+1
            temp=[]
            for key, value in dic.items():
                if value==1:
                    temp.append(key)
            if len(temp)==0:return -1
            res=[]
            for j in range(len(temp)):
                res.append(s.index(temp[j]))
            res.sort()
            return res[0]
    

Log in to reply
 

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