網頁

2024年9月15日 星期日

Python C++ bitmask解Leetcode 1371 Find the Longest Substring Containing ...


Python C++ bitmask解Leetcode 1371  Find the Longest Substring Containing Vowels in Even Counts
建構一個容器first_seen[32](5個母音考慮2**5=32),它表示第一次看到的32不同bmask的索引
[Python code請進]
-----
Build a container first_seen[32] (5 vowels to consider 2**5=32) which denotes the index for 32 different bmask first seen

class Solution:
    def findTheLongestSubstring(self, s: str) -> int:
        vow=[-1]*26
        vow[0]=0
        vow[ord('e')-ord('a')]=1
        vow[ord('i')-ord('a')]=2
        vow[ord('o')-ord('a')]=3
        vow[ord('u')-ord('a')]=4
        n=len(s)
        first_seen=[-1]*32
        first_seen[0]=0
        curr=0
        Len=0
        for i in range(n):
            x=vow[ord(s[i])-ord('a')]
            if x!=-1: curr^=(1<<x)
            if first_seen[curr]==-1: first_seen[curr]=i+1
            Len=max(Len, i+1-first_seen[curr])
        return Len
        

沒有留言:

張貼留言

HTML 編輯器