herrDeng網內搜尋

自訂搜尋

Ads

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

  1. class Solution:
  2. def findTheLongestSubstring(self, s: str) -> int:
  3. vow=[-1]*26
  4. vow[0]=0
  5. vow[ord('e')-ord('a')]=1
  6. vow[ord('i')-ord('a')]=2
  7. vow[ord('o')-ord('a')]=3
  8. vow[ord('u')-ord('a')]=4
  9. n=len(s)
  10. first_seen=[-1]*32
  11. first_seen[0]=0
  12. curr=0
  13. Len=0
  14. for i in range(n):
  15. x=vow[ord(s[i])-ord('a')]
  16. if x!=-1: curr^=(1<<x)
  17. if first_seen[curr]==-1: first_seen[curr]=i+1
  18. Len=max(Len, i+1-first_seen[curr])
  19. return Len

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章