Python: 1624. Largest Substring Between Two Equal Characters

 1624Largest 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.

substring is a contiguous sequence of characters within a string.


同樣辦法,維持一個list,長度26,每個元素儲存的是第一個index of 那個字母

走過一次string,如果發現過去有某字母已經出現,則更新最大長度,否則initiate


class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        if len(set(s))==len(s):
            return -1
        # index list
        d=[-1]*26
        
        ans=0
        for i,x in enumerate(s):
            if d[ord(x)-97]>-1:
                ans=max(ans,i-d[ord(x)-97]-1)
            else:
                d[ord(x)-97]=i
                
        return ans

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起