1876. Substrings of Size Three with Distinct Characters 不重複的長度三的子串

 1876. Substrings of Size Three with Distinct Characters 不重複的長度三的子串


contains only lowercase English letters

這個是一個很好用的辦法,可以直接用一個長度為26的list 來當作字典,儲存跟delete都是O(1)

維持一個dictionary,只有26個英文字母,之後使用sliding window approach

複雜度為O(26*n)=O(n)


ord(x)-97 可以把字母換成數字

'a'對應到0,是一個常見的技巧


喜歡歡迎追蹤頻道 和分享


class Solution:
    def countGoodSubstrings(self, s: str) -> int:
        
        
        if len(s)<=2:
            return 0
        
        d=[0]*26
        
       
        for i in range(3):
            d[ord(s[i])-97]+=1
        ans=1 if max(d)<2 else 0
            
        for i in range(3,len(s)):
            d[ord(s[i])-97]+=1
            d[ord(s[i-3])-97]-=1
            ans+=1 if max(d)<2 else 0
        
        return ans

留言

這個網誌中的熱門文章

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

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

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