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
  • 相关阅读:
    锐浪报表应用系列二
    论产品和项目
    我的处女作
    今天晚上吃什么?
    今日晚餐
    PYTHON+数据库
    周末看到小区有个阿姨溜羊驼
    AD 10使用技巧---新学习
    使用.NET进行高效率互联网敏捷开发的思考和探索【一、概述】
    【开发随感】【一】【开发基础的基础】
  • 原文地址:https://www.cnblogs.com/seyjs/p/14931213.html
Copyright © 2011-2022 走看看