⚡Flashcard Drill➔
NeetCode #80LC-1624EasyArrays & Hashing
← Back to All Problems

#80 · #1624 · Largest Substring Between Two Equal Characters(两个相同字符之间的最长子字符串)

📌 Problem Statement & Constraints

Given a string s, return the length of the longest substring between two equal characters, excluding the two characters themselves. If no such substring exists, return -1. Constraints: 1 <= s.length <= 300, lowercase letters.

💡 Core Algorithmic Approaches

  1. Only the first and last occurrence of a character can maximise the distance, so record the first occurrence of each character.
  2. Scan left to right; when a character is seen again, the gap between the two occurrences is i - first[ch] - 1.
  3. Take the maximum such gap.
  4. Record the first occurrence only the first time, otherwise later occurrences would shrink the gap.

💻 Benchmark Python3 Implementation

class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        first = {}
        best = -1
        for i, ch in enumerate(s):
            if ch in first:
                best = max(best, i - first[ch] - 1)   # exclude both endpoints
            else:
                first[ch] = i
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(k) for the first-occurrence map, k <= 26.

⚠️ Interview Pitfalls & Follow-ups

  • Overwriting first[ch] on every occurrence: the gap would collapse; only the first occurrence must be stored.
  • Forgetting to subtract 1: the characters between the endpoints are i - first[ch] - 1.
  • Returning 0 when no pair exists: the answer must be -1, and 0 is a legitimate answer for adjacent equal characters like "aa".
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

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

给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 ,计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1。子字符串是字符串中的一个连续字符序列。约束:1 ≤ s.length ≤ 300;s 只含小写英文字母。

核心要点

  • 哈希表记录首次出现位置(标准解) :遍历字符串,用字典记录每个字符 第一次 出现的下标。
  • 遇到重复字符时计算 :若当前字符 c 已在字典中,则以「首次出现位置」与「当前位置」之间的字符个数更新答案,即 i - first[c] - 1 。
  • 为什么只记录首次出现 :对固定字符 c,要使中间子串最长,应取 最左 的首次出现位置与 最右 的当前出现位置,因此首次出现位置一旦记录就不应更新。
  • 不存在时返回 -1 :答案初值设为 -1,天然处理该情况。

常见陷阱

  • 每次都更新首次出现位置 :写成 first[c] = i 无条件执行会让「首次」变成「上次」,中间子串长度被严重低估。必须只在首次出现时记录。
  • 忘记减 1 :题目要求「不含这两个字符」,因此长度是 i - first[c] - 1 而非 i - first[c] 。
  • 初值设为 0 :不存在相同字符对时应返回 -1,初值必须为 -1。
  • 误以为是「最长回文子串」 :本题只要求两端字符相同,中间内容任意,与回文无关。

参考实现

class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        first = {}
        best = -1
        for i, c in enumerate(s):
            if c in first:
                # 两个相同字符之间的字符个数
                best = max(best, i - first[c] - 1)
            else:
                first[c] = i        # 只记录首次出现
        return best