【leetcode】1624. Largest Substring Between Two Equal Characters
阿新 • • 發佈:2021-06-25
題目如下:
Given a string
s
, returnthe length of the longest substring between two equal characters, excluding the two characters.If there is no such substring return-1
.Asubstringis 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