LeetCode 题解工作台
字符串中的第一个唯一字符
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。 示例 1: 输入: s = "leetcode" 输出: 0 示例 2: 输入: s = "loveleetcode" 输出: 2 示例 3: 输入: s = "aabb" 输出: -1 提示: 1 …
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 队列·driven·状态·processing
答案摘要
我们用一个哈希表或者一个长度为 的数组 来存储每个字符出现的次数,然后从头开始遍历每个字符 ,如果 为 ,则返回 。 遍历结束后,如果没有找到符合条件的字符,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 队列·driven·状态·processing 题型思路
题目描述
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode" 输出: 0
示例 2:
输入: s = "loveleetcode" 输出: 2
示例 3:
输入: s = "aabb" 输出: -1
提示:
1 <= s.length <= 105s只包含小写字母
解题思路
方法一:计数
我们用一个哈希表或者一个长度为 的数组 来存储每个字符出现的次数,然后从头开始遍历每个字符 ,如果 为 ,则返回 。
遍历结束后,如果没有找到符合条件的字符,返回 。
时间复杂度 ,其中 是字符串的长度。空间复杂度 ,其中 是字符集,本题中字符集为小写字母,所以 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | \mathcal{O}(N) |
| 空间 | \mathcal{O}(1) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?