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
  • 相关阅读:
    django模型系统(二)
    css基础
    css进阶
    django模型系统(一)
    自定义过滤器及标签
    django模板标签
    模板变量及模板过滤器
    第六章 异常
    第三章:多态
    第三章:提高系统性能:从数据访问开始
  • 原文地址:https://www.cnblogs.com/seyjs/p/14931213.html
Copyright © 2011-2022 走看看