반응형
    
    
    
  
														Notice
														
												
											
												
												
													Recent Posts
													
											
												
												
													Recent Comments
													
											
												
												- Today
- Total
작심삼일
[LeetCode] 1249 | Minimum Remove to Make Valid Parentheses | Python 본문
728x90
    
    
  반응형
    
    
    
  문제 링크: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
문제
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
- It is the empty string, contains only lowercase characters, or
- It can be written as AB (A concatenated with B), where A and B are valid strings, or
- It can be written as (A), where A is a valid string.
조건
- 1 <= s.length <= $10^5$
- s[i] is either'(' , ')', or lowercase English letter.
내 풀이
string을 리스트로 만든다.
리스트의 각 원소를 순서대로 보면서 '('가 나왔을 경우에는 stack에 이 위치를 저장하고, ')'가 나왔을 때는 pop한다.
그리고 ')'가 나왔을 때 stack에서 pop을 할 것이 없다면 ')'를 지우면 된다.
이렇게 하면 짝이 맞지 않는 ')'는 지워지고, 짝이 맞지 않는 '('에 해당하는 위치만 stack에 저장된다.
이를 이용해 짝이 맞지 않는 '('를 지우면 된다.
코드
class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        Slist = list(s)
        stack = []
        
        for n in range(len(Slist)):
            if Slist[n] == '(':
                stack.append(n)
            elif Slist[n] == ')':
                if len(stack):
                    stack.pop()
                else:
                    Slist[n] = ''
            
        for idx in stack:
            Slist[idx] = ''
        
        return ''.join(Slist)728x90
    
    
  반응형
    
    
    
  '스터디 > 코테' 카테고리의 다른 글
| [LeetCode] 856 | Score of Parentheses | Python (0) | 2022.03.17 | 
|---|---|
| [LeetCode] 946 | Validate Stack Sequences | Python (0) | 2022.03.16 | 
| [LeetCode] 71 | Simplify Path | Python (0) | 2022.03.14 | 
| [LeetCode] 61 | Rotate List | Python (0) | 2022.03.11 | 
| [LeetCode] 2 | Add Two Numbers | Python (0) | 2022.03.10 | 
			  Comments
			
		
	
               
           
					
					
					
					
					
					
				