LeetCode 题解工作台

第一个出现两次的字母

给你一个由小写英文字母组成的字符串 s ,请你找出并返回第一个出现 两次 的字母。 注意: 如果 a 的 第二次 出现比 b 的 第二次 出现在字符串中的位置更靠前,则认为字母 a 在字母 b 之前出现两次。 s 包含至少一个出现两次的字母。 示例 1: 输入: s = "abccbaacz" 输出…

category

4

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

遍历字符串 ,用数组或哈希表 `cnt` 记录每个字母出现的次数,当某个字母出现两次时,返回该字母。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度,而 为字符集大小。本题中 $C = 26$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由小写英文字母组成的字符串 s ,请你找出并返回第一个出现 两次 的字母。

注意:

  • 如果 a第二次 出现比 b第二次 出现在字符串中的位置更靠前,则认为字母 a 在字母 b 之前出现两次。
  • s 包含至少一个出现两次的字母。

 

示例 1:

输入:s = "abccbaacz"
输出:"c"
解释:
字母 'a' 在下标 0 、5 和 6 处出现。
字母 'b' 在下标 1 和 4 处出现。
字母 'c' 在下标 2 、3 和 7 处出现。
字母 'z' 在下标 8 处出现。
字母 'c' 是第一个出现两次的字母,因为在所有字母中,'c' 第二次出现的下标是最小的。

示例 2:

输入:s = "abcdd"
输出:"d"
解释:
只有字母 'd' 出现两次,所以返回 'd' 。

 

提示:

  • 2 <= s.length <= 100
  • s 由小写英文字母组成
  • s 包含至少一个重复字母
lightbulb

解题思路

方法一:数组或哈希表

遍历字符串 ss,用数组或哈希表 cnt 记录每个字母出现的次数,当某个字母出现两次时,返回该字母。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为字符串 ss 的长度,而 CC 为字符集大小。本题中 C=26C = 26

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

复杂度分析

指标
时间complexity is O(n) where n is the length of the string, since each character is processed once. Space complexity is O(1) if using a 26-bit mask or O(k) for a hash set with k unique letters.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for O(n) solution using a hash table or bitmask.

  • question_mark

    Expect early return as soon as a repeat is detected.

  • question_mark

    Consider edge cases with multiple repeated letters.

warning

常见陷阱

外企场景
  • error

    Returning the first seen character instead of the first to repeat.

  • error

    Failing to handle strings where the repeated character is at the end.

  • error

    Using nested loops, resulting in O(n^2) time instead of O(n).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the first character to appear k times instead of twice.

  • arrow_right_alt

    Find the first repeated substring of length 2 or more.

  • arrow_right_alt

    Determine the last character to repeat instead of the first.

help

常见问题

外企场景

第一个出现两次的字母题解:哈希·表·结合·string | LeetCode #2351 简单