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
  • 相关阅读:
    2018/12/06 L1-031 到底是不是太胖了 Java
    2018/12/06 L1-030 一帮一 Java
    2018/12/06 L1-029 是不是太胖了 Java
    .NET Framework 类库命名空间
    .NET获取根目录
    ddd领域驱动设计
    垃圾回收
    rest api
    数据库ACID
    事务隔离级别
  • 原文地址:https://www.cnblogs.com/seyjs/p/14931213.html
Copyright © 2011-2022 走看看