describe
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.
Copy the code
Example 2:
Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".
Copy the code
Example 3:
Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.
Copy the code
Example 4:
Input: s = "cabbac"
Output: 4
Explanation: The optimal substring here is "abba". Other non-optimal substrings include "bb" and "".
Copy the code
Note:
1 <= s.length <= 300
s contains only lowercase English letters.
Copy the code
parsing
If there is no such thing, return -1. If there is no such thing, return -1. If there is no such thing, return -1. If the length of value in count is greater than 1, find the farthest distance. After the traversal, you can get the answer.
answer
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
Copy the code
The results
Runtime: 16 ms, Faster than 84.87% of Python online submissions for Largest Substring Between Two Equal Characters. Memory Usage: Each node in the Python online submission for Largest Substring Between Two Equal Characters.Copy the code
Original link: leetcode.com/problems/la…
Your support is my biggest motivation