defisValid(self, s: str) -> bool: right = { ')': '(', '}': '{', ']': '[' } stack = [] for c in s: # left bracket if c notin right: stack.append(c) # right bracket elifnot stack or stack.pop() != right[c]: returnFalse returnnot stack
1249. Minimum Remove to Make Valid Parentheses
for right bracket, must match to an existed left bracket, or remove it.
for left bracket, log its index After scan the whole string, remove open left bracket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defminRemoveToMakeValid(self, s: str) -> str: open_left = [] res = '' for c in s: if c == '(': res += c open_left.append(len(res) - 1) elif c == ')': if open_left: res += c open_left.pop() else: res += c for i inreversed(open_left): res = res[:i] + res[i + 1: ] return res
defdecodeString(self, s: str) -> str: stack = [] for c in s: if c == ']': repeat = '' while stack: x = stack.pop() # found substring if x == '[': # find number num = '' while stack and stack[-1].isdigit(): num = stack.pop() + num num = int(num) repeat = repeat * int(num) stack.append(repeat) break repeat = x + repeat else: stack.append(c) return''.join(stack)
1209. Remove All Adjacent Duplicates in String II
1 2 3 4 5 6 7 8 9 10 11 12
defremoveDuplicates(self, s: str, k: int) -> str: stack = [] # (element, cnt) for c in s: if stack and c == stack[-1][0]: cnt = stack[-1][1] + 1 stack.append((c, cnt)) if cnt == k: for _ inrange(k): stack.pop() else: stack.append((c, 1)) return''.join([x[0] for x in stack])
739. Daily Temperatures
use index to calculate days
1 2 3 4 5 6 7 8 9
defdailyTemperatures(self, T: List[int]) -> List[int]: stack = [] # temp, index warmer = [0] * len(T) for i, temp inenumerate(T): while stack and temp > stack[-1][0]: pre_temp, j = stack.pop() warmer[j] = i - j stack.append((temp, i)) return warmer
71. Simplify Path
1 2 3 4 5 6 7 8 9 10 11 12 13
defsimplifyPath(self, path: str) -> str: stack = [] paths = path.split('/') for p in paths: if p == '..': if stack: stack.pop() continue elif p == '.'or p == '': continue else: stack.append(p) return'/' + '/'.join(stack)