algorithm

921. Minimum Add to Make Parentheses Valid

식피두 2020. 10. 20. 09:06

leetcode.com/problems/minimum-add-to-make-parentheses-valid/

 

Minimum Add to Make Parentheses Valid - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

())(() 와 같이 parentheses가 주어졌을 때,

valid하게 만들기 위해서 몇 개를 추가해야 하는가?

구하는 문제, medium 으로 되어 있지만 easy 수준으로 정말 간단하다.

 

32ms

class Solution:
    def minAddToMakeValid(self, S: str) -> int:
        stack = []
        for c in S:
            if not stack:
                stack.append(c)
                continue
            if stack[-1] == '(' and c == ')':
                stack.pop()
            else:
                stack.append(c)
            
        return len(stack)            
            

 

20ms

와... ( 를 +, ) 를 -로 해석해서 더 빠르게 푼 방법

class Solution:
    def minAddToMakeValid(self, S: str) -> int:
        add = 0
        ex = 0
        for s in S:
            if s == "(":
                add += 1
            elif s == ")" and add <= 0:
                ex += 1
                add = 0
            else:
                add -= 1
        return add+ex

'algorithm' 카테고리의 다른 글

785. Is Graph Bipartite?  (0) 2020.11.01
1190. Reverse Substrings Between Each Pair of Parentheses  (0) 2020.10.25
496. Next Greater Element I  (0) 2020.10.20
1544. Make The String Great  (0) 2020.10.18
735. Asteroid Collision  (0) 2020.10.18