LeetCode 题解工作台

最长的美好子字符串

当一个字符串 s 包含的每一种字母的大写和小写形式 同时 出现在 s 中,就称这个字符串 s 是 美好 字符串。比方说, "abABB" 是美好字符串,因为 'A' 和 'a' 同时出现了,且 'B' 和 'b' 也同时出现了。然而, "abA" 不是美好字符串因为 'b' 出现了,而 'B' 没有…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们可以直接枚举所有子串的起点位置 ,找到以该位置所在的字符为首字符的所有子串,用哈希表 记录子串的所有字符。 如果子串中存在一个字母找不到对应的大写字母或者小写字母,那么不满足条件,否则取最长的且最早出现的子串。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

当一个字符串 s 包含的每一种字母的大写和小写形式 同时 出现在 s 中,就称这个字符串 s 是 美好 字符串。比方说,"abABB" 是美好字符串,因为 'A' 和 'a' 同时出现了,且 'B' 和 'b' 也同时出现了。然而,"abA" 不是美好字符串因为 'b' 出现了,而 'B' 没有出现。

给你一个字符串 s ,请你返回 s 最长的 美好子字符串 。如果有多个答案,请你返回 最早 出现的一个。如果不存在美好子字符串,请你返回一个空字符串。

 

示例 1:

输入:s = "YazaAay"
输出:"aAa"
解释:"aAa" 是一个美好字符串,因为这个子串中仅含一种字母,其小写形式 'a' 和大写形式 'A' 也同时出现了。
"aAa" 是最长的美好子字符串。

示例 2:

输入:s = "Bb"
输出:"Bb"
解释:"Bb" 是美好字符串,因为 'B' 和 'b' 都出现了。整个字符串也是原字符串的子字符串。

示例 3:

输入:s = "c"
输出:""
解释:没有美好子字符串。

示例 4:

输入:s = "dDzeE"
输出:"dD"
解释:"dD" 和 "eE" 都是最长美好子字符串。
由于有多个美好子字符串,返回 "dD" ,因为它出现得最早。

 

提示:

  • 1 <= s.length <= 100
  • s 只包含大写和小写英文字母。
lightbulb

解题思路

方法一:枚举 + 哈希表

我们可以直接枚举所有子串的起点位置 ii,找到以该位置所在的字符为首字符的所有子串,用哈希表 ss 记录子串的所有字符。

如果子串中存在一个字母找不到对应的大写字母或者小写字母,那么不满足条件,否则取最长的且最早出现的子串。

时间复杂度 O(n2×C)O(n^2 \times C),空间复杂度 O(C)O(C)。其中 nn 为字符串 ss 的长度,而 CC 为字符集的大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def longestNiceSubstring(self, s: str) -> str:
        n = len(s)
        ans = ''
        for i in range(n):
            ss = set()
            for j in range(i, n):
                ss.add(s[j])
                if (
                    all(c.lower() in ss and c.upper() in ss for c in ss)
                    and len(ans) < j - i + 1
                ):
                    ans = s[i : j + 1]
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks if the candidate understands the sliding window technique with dynamic state updates.

  • question_mark

    Tests the candidate's ability to optimize brute force approaches into efficient solutions.

  • question_mark

    Looks for a clear explanation of edge cases and handling them correctly.

warning

常见陷阱

外企场景
  • error

    Not correctly tracking the running state of characters inside the sliding window.

  • error

    Failing to handle edge cases, such as strings that have no nice substrings or strings of length 1.

  • error

    Using a brute force approach without optimizing the substring search using the sliding window.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider optimizing this solution further for larger strings or varying constraints.

  • arrow_right_alt

    Try solving the problem using a divide and conquer strategy.

  • arrow_right_alt

    Explore the possibility of using bit manipulation for state representation.

help

常见问题

外企场景

最长的美好子字符串题解:滑动窗口(状态滚动更新) | LeetCode #1763 简单