描述
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 "".
Note:
1 <= s.length <= 300
s contains only lowercase English letters.
解析
根据题意,就是找出两个相同字符中间的间隔距离,如果不存在返回 -1 ,思路简单,就是用字典 count 来对每个出现的字符进行索引位置的存储,key 为字符,value 为索引列表,然后遍历 count 中 value 的长度大于 1 的字符,找出最远的距离,遍历结束,即可得到答案。
解答
class Solution(object):
def maxLengthBetweenEqualCharacters(self, s):
"""
:type s: str
:rtype: int
"""
if len(set(s)) == len(s):
return -1
count = {}
for i,c in enumerate(s):
if c not in count:
count[c] = [i]
else:
count[c].append(i)
r = -1
for k,v in count.items():
if len(v) > 1:
r = max( r, v[-1]-v[0]-1)
return r
运行结果
Runtime: 16 ms, faster than 84.87% of Python online submissions for Largest Substring Between Two Equal Characters.
Memory Usage: 13.3 MB, less than 98.32% of Python online submissions for Largest Substring Between Two Equal Characters.
原题链接:leetcode.com/problems/la…
您的支持是我最大的动力