requirements

Given a string, find its first non-repeating character and return its index. If none exists, -1 is returned.

Example:

S = "leetcode" returns 0. S = "loveleetcode" returns 2Copy the code

Tip: You can assume that the string contains only lowercase letters.

The core code

class Solution:
    def firstUniqChar(self, s: str) - >int:
        import collections
        dic = collections.Counter(s)
        for i,char in enumerate(s):
            if dic[char] == 1:
                return i
        return -1
Copy the code

Another solution

class Solution:
    def firstUniqChar(self, s: str) - >int:
        l = len(s)
        for item in "abcdefghijklmnopqrstuvwxyz":
            a = s.find(item)
            b = s.rfind(item)
            if a == b anda ! = -1:
                l = min(l,a)
        return l if l < len(s) else -1
Copy the code

First solution: we use the Collections Counter method, count the number of characters per character, then iterate through the string, output one character, and return -1 for none. The second solution: if the output is limited to lowercase letters: then you can find the most left subscript and most right subscript of each letter. If the most left subscript == the most right subscript, then the number of occurrences is 1, the idea is relatively clear and worth learning.