2696
class Solution:
def minLength(self, s: str) -> int:
while 'AB' in s or 'CD' in s:
# s.replace(a, b) 将s中的a换成b,连续使用s.r().r()
s = s.replace('AB', '').replace('CD', '')
return len(s)
class Solution:
def minLength(self, s: str) -> int:
# 用栈保存遍历过的字符,
# 如果当前字母是B 栈顶是A 那么两个都删掉
st = []
for c in s:
if st and ((c == 'B' and st[-1] == 'A') or (c == 'D' and st[-1] == 'C')):
st.pop() # 不操作c 删掉栈顶!
else:
st.append(c)
return len(st)
1047
so easy
class Solution:
def removeDuplicates(self, s: str) -> str:
# 用栈保存遍历过的字符,
# 如果当前元素与栈顶元素相同 两个都删掉
st = []
for c in s:
if st and ((c == st[-1]) or (c == st[-1])):
st.pop()
else:
st.append(c)
return ''.join(st)
1544
class Solution:
def makeGood(self, s: str) -> str:
stack = []
for char in s: # eE不可以 Ee也不可以! 前一个元素入栈 所以对比的是栈顶和当前元素!
if stack and ((char.islower() and stack[-1].isupper() and char.upper() == stack[-1]) or (char.isupper() and stack[-1].islower() and char.lower() == stack[-1])):
stack.pop()
else:
stack.append(char)
return ''.join(stack)
1544
class Solution:
def isValid(self, s: str) -> bool:
# 类似判断括号是否合法,插入括号改为了插入'abc'
# 'a' 类似左括号 直接入栈
# 'b'如果栈为空,或者栈顶不是a,则直接返回false,否则将栈顶修改为b
# 'C'如果栈为空,或者栈顶不是b,则直接返回false,否则弹出栈顶,相当于找到了1次abc
st = []
for cur in map(ord, s):
if cur > ord('a') and (len(st) == 0 or cur - st.pop() != 1):
return False
# 如果是a/b,入栈
if cur < ord('c'):
st.append(cur)
# return True 错了!!!输入s = "aaabc"最后要看栈是否为空
return len(st) == 0