Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-10-09 09:12:18
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid
921. Minimum Add to Make Parentheses Valid
以下三种小括号字串是有效的:
1.空字串
2.只有英文字母的字串
3.(A) 就是左右括号这种样子的字串
你可以在字串任何位置插入括号
请回传使s变成有效字串的最小插入次数
思路:
stack 用stack存取字符
如若出现()这种状况 就result-1
其他状况代表要变动 result+1
Python Code:
class Solution:
def minAddToMakeValid(self, s: str) -> int:
if "(" not in s and ")" not in s:
return 0
result = 0
stack = []
for b in s:
if not stack:
stack.append(b)
result +=1
elif stack[-1] == "(" and b == ")":
stack.pop()
result -= 1
else:
stack.append(b)
result +=1
return result
感觉有更漂亮的写法 但先这样:))))
作者: oin1104 (是oin的说)   2024-10-09 09:15:00
宝 我好崇拜你

Links booklink

Contact Us: admin [ a t ] ucptt.com