動機

複習Counter

Problem

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = leetcodeOutput: 0

Example 2:

Input: s = loveleetcodeOutput: 2

Example 3:

Input: s = aabbOutput: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Sol

class Solution:
    def firstUniqChar(self, s: str) -> int:
        f = [k for (k,v) in Counter(s).items() if v == 1]
        if f:
            for i in range(len(s)):
                if s[i] in f:
                    return i
        return -1