题目链接:2696. 删除子串后的字符串最小长度 - 力扣(LeetCode)
解题思路:
1、暴力破解
就是每次用一个signal,表明这个过程是否有改动,如果有改动那么继续遍历,如果上一轮没有改动那么就直接返回。
class Solution:
def minLength(self, s: str) -> int:
map = [0] * len(s)
tmp = s
while True:
singal = 0 //记录是否有删改
for i in range(0,len(tmp)-1):
if tmp[i] == 'A' and tmp[i+1] == 'B':
map[i] = 1
map[i+1] = 1
singal = 1
if tmp[i] == 'C' and tmp[i+1] == 'D':
map[i] = 1
map[i+1] = 1
singal = 1
x = tmp
tmp = ''
for i in range(0,len(x)):
if map[i] == 0 :
tmp += x[i]
map = [0] * len(tmp)
if singal == 0:
return len(tmp)
2、滑动窗口
思路:AB和CD的长度都为2,那么可以设置一个大小为2的滑动窗口,沿着字符串s从左到右依次检查,如果发现目标子串,则s的长度n减去2,当前索引i向后退2步,如果索引i=0,那么退1步。
class Solution:
def minLength(self, s: str) -> int:
n = len(s)
i = 0
while i < n:
s1 = s[i:i+2]
if s1 == 'AB' or s1 == 'CD':
s = s[:i] + s[i+2:]
n -= 2
i = -1 if i == 0 else i - 2
i += 1
return len(s)