N = len(A) res = 0 left, right = 0, 0 zeros = 0 while right < N: if A[right] == 0: zeros += 1 while zeros > K: if A[left] == 0: zeros -= 1 left += 1 res = max(res, right - left + 1) right += 1 return res
classSolution: deflongestSubarray(self, nums, limit): r = l = res = 0 min_q = collections.deque() max_q = collections.deque() for num in nums: while len(min_q) and num < min_q[-1]: min_q.pop() while len(max_q) and num > max_q[-1]: max_q.pop() min_q.append(num) max_q.append(num) r += 1; while max_q[0] - min_q[0] > limit: if min_q[0] == nums[l]: min_q.popleft() if max_q[0] == nums[l]: max_q.popleft() l += 1 res = max(res, r - l) return res
classSolution: defflipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for line in A: l, r = 0, len(line) - 1 while l < r: if line[l] == line[r]: line[l] = line[r] = (1 ^ line[l]) l += 1 r -= 1 if l == r: line[l] ^= 1 return A
classSolution: deffindNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: for i in range(len(puzzles)): tmp = 0 for ch in puzzles[i]: tmp |= (1 << ord(ch) - ord('a')) puzzles[i] = (tmp, puzzles[i][0]) for i in range(len(words)): tmp = 0 for ch in words[i]: tmp |= (1 << ord(ch) - ord('a')) words[i] = tmp for i in range(len(puzzles)): p = puzzles[i] match = 0 for w in words: if (w >> (ord(p[1]) - ord('a'))) & 1and w == (w & p[0]): match += 1 puzzles[i] = match return puzzles
for word in words: mask = 0 for ch in word: mask |= (1 << (ord(ch) - ord("a"))) if str(mask).count("1") <= 7: frequency[mask] += 1 ans = list() for puzzle in puzzles: total = 0
# 枚举子集方法一 # for choose in range(1 << 6): # mask = 0 # for i in range(6): # if choose & (1 << i): # mask |= (1 << (ord(puzzle[i + 1]) - ord("a"))) # mask |= (1 << (ord(puzzle[0]) - ord("a"))) # if mask in frequency: # total += frequency[mask]
# 枚举子集方法二 mask = 0 for i in range(1, 7): mask |= (1 << (ord(puzzle[i]) - ord("a"))) subset = mask while subset: s = subset | (1 << (ord(puzzle[0]) - ord("a"))) if s in frequency: total += frequency[s] subset = (subset - 1) & mask # 在枚举子集的过程中,要么会漏掉全集 mask,要么会漏掉空集 # 这里会漏掉空集,因此需要额外判断空集 if (1 << (ord(puzzle[0]) - ord("a"))) in frequency: total += frequency[1 << (ord(puzzle[0]) - ord("a"))]
给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。
classSolution(object): deflongestSubstring(self, s, k): if len(s) < k: return0 for c in set(s): if s.count(c) < k: return max(self.longestSubstring(t, k) for t in s.split(c)) return len(s)
f = [envelopes[0][1]] for i in range(1, n): if (num := envelopes[i][1]) > f[-1]: f.append(num) else: index = bisect.bisect_left(f, num) f[index] = num return len(f)
classSolution: defremoveDuplicates(self, S: str) -> str: stack = [] for i in list(S): if stack and stack[-1] == i: stack.pop() else: stack.append(i) return''.join(stack)