387. 字符串中的第一个唯一字符

发布时间 2023-10-23 14:24:48作者: Frommoon

题目

  • 给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

示例 1:

输入: s = "leetcode"
输出: 0

示例 2:

输入: s = "loveleetcode"
输出: 2

示例 3:

输入: s = "aabb"
输出: -1

法一、字典

class Solution:
    def firstUniqChar(self, s: str) -> int:
        dic = {}
        for c in s:#遍历字符串中的每个字符   
            if c not in dic:#如果字符不在字典里,写入字典,并赋值True
                dic[c] = True
            else:#如果字符已经在字典里了,修改字典对应的值为False
                dic[c] = False

        for i, c in enumerate(s):#遍历字符串中的每个字符   
            if dic[c] == True:#找到第一个值为True的下标并返回
                return i
        return -1#如果遍历完没找到值为True的,返回-1

法二、计数

class Solution:
    def firstUniqChar(self, s: str) -> int:
        char_count = {}
        for char in s:
            if char in char_count:
                char_count[char] += 1
            else:
                char_count[char] = 1

        for i, char in enumerate(s):
            if char_count[char] == 1:
                return i

        return -1
  • Counter类计数
from collections import Counter

class Solution:
    def firstUniqChar(self, s: str) -> int:
        cnt = Counter(s)#将字符串 s 转化为一个计数器对象 cnt,其中每个字符作为键,出现的次数作为值。
        for i, char in enumerate(s):
            if cnt[char] == 1:
                return i
        return -1

法三、字符串内置函数rindex()

  • index():用于查找字符串中指定值第一次出现的位置
  • rindex():用于查找字符串中指定值最后一次出现的位置
class Solution:
    def firstUniqChar(self, s: str) -> int:
        for i, char in enumerate(s):
            if s.index(char) == s.rindex(char):
                return i
        return -1