LeetCode 题解工作台

两个相同字符之间的最长子字符串

给你一个字符串 s ,请你返回 两个相同字符之间的最长子字符串的长度 , 计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1 。 子字符串 是字符串中的一个连续字符序列。 示例 1: 输入: s = "aa" 输出: 0 解释: 最优的子字符串是两个 'a' 之间的空子字符串。 示例 2…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

用数组或哈希表记录字符串 每个字符第一次出现的位置。由于本题中字符串 只含小写英文字母,因此可以用一个长度为 的数组 来记录,初始时数组元素值均为 。 遍历字符串 中每个字符 ,若 在数组中的值为 ,则更新为当前位置 ;否则我们将答案更新为当前位置 与数组中的值 的差值的最大值减一,即 $ans = \max (ans, i - d[c]-1)$。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1

子字符串 是字符串中的一个连续字符序列。

 

示例 1:

输入:s = "aa"
输出:0
解释:最优的子字符串是两个 'a' 之间的空子字符串。

示例 2:

输入:s = "abca"
输出:2
解释:最优的子字符串是 "bc" 。

示例 3:

输入:s = "cbzxy"
输出:-1
解释:s 中不存在出现出现两次的字符,所以返回 -1 。

示例 4:

输入:s = "cabbac"
输出:4
解释:最优的子字符串是 "abba" ,其他的非最优解包括 "bb" 和 "" 。

 

提示:

  • 1 <= s.length <= 300
  • s 只含小写英文字母
lightbulb

解题思路

方法一:数组或哈希表

用数组或哈希表记录字符串 ss 每个字符第一次出现的位置。由于本题中字符串 ss 只含小写英文字母,因此可以用一个长度为 2626 的数组 dd 来记录,初始时数组元素值均为 1-1

遍历字符串 ss 中每个字符 cc,若 cc 在数组中的值为 1-1,则更新为当前位置 ii;否则我们将答案更新为当前位置 ii 与数组中的值 d[c]d[c] 的差值的最大值减一,即 ans=max(ans,id[c]1)ans = \max (ans, i - d[c]-1)

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

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        d = {}
        ans = -1
        for i, c in enumerate(s):
            if c in d:
                ans = max(ans, i - d[c] - 1)
            else:
                d[c] = i
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate should demonstrate understanding of hash table usage in strings.

  • question_mark

    The candidate should be able to quickly identify when no solution exists.

  • question_mark

    A solid candidate would optimize the process by eliminating unnecessary calculations.

warning

常见陷阱

外企场景
  • error

    Forgetting to exclude the two equal characters when calculating the substring length.

  • error

    Over-complicating the problem by using unnecessary data structures or algorithms.

  • error

    Failing to handle edge cases like strings of length 1 or strings with no repeated characters.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the string contains uppercase letters? How would you handle it?

  • arrow_right_alt

    How would this solution scale if the string is a very large dataset (e.g., millions of characters)?

  • arrow_right_alt

    What if the problem required finding the longest substring between two equal characters of different types (e.g., digits or symbols)?

help

常见问题

外企场景

两个相同字符之间的最长子字符串题解:哈希·表·结合·string | LeetCode #1624 简单