23.04.10 Today’s Leetcode
20. Valid Parentheses (easy)
with Stack
class Solution:
def isValid(self, s: str) -> bool:
stack = []
open_ = '({['
close_ = ']})'
for p in s:
if p in open_:
stack.append(p)
if p in close_:
c = ''
if stack:
c = stack.pop()
if c == '[' and p == ']':
continue
if c == '(' and p == ')':
continue
if c == '{' and p == '}':
continue
return False
return len(stack) == 0
2337. Move Pieces to Obtain a String (medium), 777. Swap Adjacent in LR String (medium)
Two problems are exactly equal
class Solution:
def canChange(self, start: str, target: str) -> bool:
m = [char for char in start if char != '_']
n = [char for char in target if char != '_']
if m != n:
return False
def help(s):
pos_l, pos_r = [], []
for index, char in enumerate(s):
if char == 'L':
pos_l.append(index)
if char == 'R':
pos_r.append(index)
return pos_l, pos_r
a, b = help(start)
c, d = help(target)
if len(a) != len(c) or len(b) != len(d):
return False
for i in range(len(a)):
if c[i] > a[i]:
return False
for i in range(len(b)):
if d[i] < b[i]:
return False
return True
332. Remove Palindromic Subsequences (easy)
class Solution:
def removePalindromeSub(self, s):
return 2 - (s == s[::-1]) - (s == "")