LeetCode 题解工作台

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

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。 示例 1: 输入: s = "leetcode" 输出: 0 示例 2: 输入: s = "loveleetcode" 输出: 2 示例 3: 输入: s = "aabb" 输出: -1 提示: 1 …

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 队列·driven·状态·processing

bolt

答案摘要

我们用一个哈希表或者一个长度为 的数组 来存储每个字符出现的次数,然后从头开始遍历每个字符 ,如果 为 ,则返回 。 遍历结束后,如果没有找到符合条件的字符,返回 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 队列·driven·状态·processing 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

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

示例 3:

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

 

提示:

  • 1 <= s.length <= 105
  • s 只包含小写字母
lightbulb

解题思路

方法一:计数

我们用一个哈希表或者一个长度为 2626 的数组 cnt\text{cnt} 来存储每个字符出现的次数,然后从头开始遍历每个字符 s[i]\text{s[i]},如果 cnt[s[i]]\text{cnt[s[i]]}11,则返回 ii

遍历结束后,如果没有找到符合条件的字符,返回 1-1

时间复杂度 O(n)O(n),其中 nn 是字符串的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 是字符集,本题中字符集为小写字母,所以 Σ=26|\Sigma|=26

1
2
3
4
5
6
7
8
class Solution:
    def firstUniqChar(self, s: str) -> int:
        cnt = Counter(s)
        for i, c in enumerate(s):
            if cnt[c] == 1:
                return i
        return -1
speed

复杂度分析

指标
时间\mathcal{O}(N)
空间\mathcal{O}(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate effectively demonstrates the ability to use a hash table for frequency counting.

  • question_mark

    Candidate efficiently handles the queue to maintain order for character processing.

  • question_mark

    Candidate avoids unnecessary computations and keeps the algorithm within the required time and space complexity.

warning

常见陷阱

外企场景
  • error

    Misusing a stack instead of a queue, which may lead to incorrect order processing of characters.

  • error

    Not handling edge cases, like strings with all repeating characters.

  • error

    Overcomplicating the solution, such as by using nested loops or unnecessary data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the string contains uppercase letters?

  • arrow_right_alt

    What if we need to find the second unique character instead?

  • arrow_right_alt

    What if the string is very large, and performance optimization is required?

help

常见问题

外企场景

字符串中的第一个唯一字符题解:队列·driven·状态·processing | LeetCode #387 简单