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
[codes on Leetcode]https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/solutions/5788042/prefix-sum-with-xor-for-bit-mask-11-ms-beats-99-53/
[bit/ bitmask play list]https://www.youtube.com/watch?v=Hw1fnQA8Nk8&list=PLYRlUBnWnd5K8FlzJ6tOswqQcsk7R1Duh
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
沒有留言:
張貼留言