leetcode 387. The first unique string of characters (Python)

Topic Link

Subject description:

Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.

Case:

s = "leetcode"
return 0.

s = "loveleetcode",
return to 2.

Problem-solving ideas:

Iterate over the string, the number of times each character appears with the character into the dictionary,
traverse the string again, find the number for the first character returns its index of 1
ps Since dictionaries are unordered, so the second time to the first number of enumeration string instead of the character dictionary 1

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        rr=-1
        res={}
        for i in s:
            if i in res:
                res[i]+=1
            else:
                res[i]=1
        for i in s:
            if res[i]==1:
                return s.index(i)
        return -1

Here Insert Picture Description
ps
practices of others
find () to find the index of the first occurrence of the character, rfind () to find the index of the last occurrence of the character, if the two values are equal and not equal to -1 indicates that the character appears only once, only once all the alphabetical index into the list, which returns the minimum value

        alpha='qwertyuiopasdfghjklzxcvbnm'
        s=[s.find(i) for i in alpha if s.find(i)==s.rfind(i) and s.find(i)!=-1]
        return min(s) if s else -1

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/90812121