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

1.题目描述

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

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


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


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


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


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


提示:

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

2.思路分析

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

对于字符 c h ch ch,只需要求出 c h ch ch 第一次出现在字符串中的索引位置 f i r s t first first 和最后一次出现在字符串中的索引位置 l a s t last last,则以 c h ch ch 为相同字符之间的子字符串的最大长度一定为 l a s t − f i r s t − 1 last−first−1 lastfirst1,依次求出所有可能的子字符的长度的最大值即可。

设数组 f i r s t I n d e x firstIndex firstIndex 记录每个字符 i i i 在字符串中第一次出现的索引, m a x L e n g t h maxLength maxLength 表示当前子字符串的最大长度。

  • 初始化时 f i r s t I n d e x firstIndex firstIndex 中的每个元素都初始化为 − 1 −1 1,表示该字符还未出现。

  • 当遍历到第 i i i 个字符 c h ch ch 时:

    • 如果当前数组中 f i r s t I n d e x [ c h ] = − 1 firstIndex[ch]=−1 firstIndex[ch]=1,则记录该字符第一次出现的索引为 i i i,更新 f i r s t I n d e x [ c h ] = 1 firstIndex[ch]=1 firstIndex[ch]=1
    • 如果当前数组中 f i r s t I n d e x [ c h ] ≥ 0 firstIndex[ch]≥0 firstIndex[ch]0 时,则表示字符 c h ch ch 之前已经出现过,此时两个 c h ch ch 之间的子字符串长度为 i − f i r s t I n d e x [ c h ] − 1 i−firstIndex[ch]−1 ifirstIndex[ch]1,同时更新 m a x L e n g t h maxLength maxLength
  • 返回最大的长度 m a x L e n g t h maxLength maxLength 即可。

在这里插入图片描述

3.代码实现

class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        result = -1
        firstIndex = {
    
    }
        for i, c in enumerate(s):
            if c not in firstIndex:
                firstIndex[c] = i
            else:
                result = max(result, i - firstIndex[c] - 1)
        return result

复杂度分析:

  • 时间复杂度:O(n),其中 n 表示字符串的长度。只需遍历一遍字符串即可。

  • 空间复杂度: O ( ∣ Σ ∣ ) O(\vert\Sigma\vert) O(∣Σ∣),其中 Σ \Sigma Σ 是字符集,在本题中字符集为所有小写字母, ∣ Σ ∣ \vert\Sigma\vert ∣Σ∣ =26。

猜你喜欢

转载自blog.csdn.net/weixin_44852067/article/details/126902233
今日推荐