zoukankan      html  css  js  c++  java
  • 【leetcode】1624. Largest Substring Between Two Equal Characters

    题目如下:

    Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.

    A substring is a contiguous sequence of characters within a string.

    Example 1:

    Input: s = "aa"
    Output: 0
    Explanation: The optimal substring here is an empty substring between the two 'a's.

    Example 2:

    Input: s = "abca"
    Output: 2
    Explanation: The optimal substring here is "bc".
    

    Example 3:

    Input: s = "cbzxy"
    Output: -1
    Explanation: There are no characters that appear twice in s.
    

    Example 4:

    Input: s = "cabbac"
    Output: 4
    Explanation: The optimal substring here is "abba". Other non-optimal substrings include "bb" and "".

    Constraints:

    • 1 <= s.length <= 300
    • s contains only lowercase English letters.

    解题思路:遍历s,记录每个字符最早出现的位置,遇到相同的字符的时候,找出第一个字符出现的位置,两者之间即为符合条件的一个子串,求出最大值即可。

    代码如下:

    class Solution(object):
        def maxLengthBetweenEqualCharacters(self, s):
            """
            :type s: str
            :rtype: int
            """
            dic_last_inx = {}
            res = -1
            for i in range(len(s)):
                if s[i] not in dic_last_inx:
                    dic_last_inx[s[i]] = i
                else:
                    res = max(res,i - dic_last_inx[s[i]] - 1)
            return res
  • 相关阅读:
    P1410 子序列 (动态规划)
    P2085 最小函数值 (堆)
    [ZJOI2007]棋盘制作 (单调栈,动态规划)
    [ZJOI2005]午餐 (贪心,动态规划)
    黑匣子_NOI导刊2010提高 (对顶堆)
    [BZOJ1455] 罗马游戏 (左偏树||并查集)
    P1651 塔 (动态规划)
    两类斯特林数 (组合数学)
    从编程到工程
    失败的过程也是过程
  • 原文地址:https://www.cnblogs.com/seyjs/p/14931213.html
Copyright © 2011-2022 走看看