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

题目

  • 给定一个字符串 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
posted @   Frommoon  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示