본문 바로가기
공부하며놀자/프로그래밍

[leetcode] 20. Valid Parentheses

by 테너토너 2021. 1. 22.

20. Valid Parentheses

Easy

6619269Add to ListShare

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

 

Example 1:

Input: s = "()" Output: true

Example 2:

Input: s = "()[]{}" Output: true

Example 3:

Input: s = "(]" Output: false

Example 4:

Input: s = "([)]" Output: false

Example 5:

Input: s = "{[]}" Output: true

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

max length는 왜 필요한지 모르겠다..

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) == 1:
            return False
            
        pairs = {")":"(", "}":"{", "]":"["}
        open_p = ["(","{","["]
        stack = []
        for e in s:
            if e in open_p:
                stack.append(e)
            else:
                if stack:
                    if stack[-1] == pairs[e]:
                        stack.pop()
                    else:
                        stack.append(e)
                else:
                    stack.append(e)

        if not stack:
            return True
        else:
            return False
                

 

길이가 1일 때 실패, stack이 아무것도 없을 때 -1로 마지막 element 읽어 오면서 fail나서 총 두번 실패.

 

Success

Details 

Runtime: 32 ms, faster than 63.36% of Python3 online submissions for Valid Parentheses.

Memory Usage: 14.3 MB, less than 67.00% of Python3 online submissions for Valid Parentheses.

Next challenges:

Generate ParenthesesLongest Valid ParenthesesRemove Invalid ParenthesesCheck If Word Is Valid After Substitutions

Show off your acceptance:

 

 

Time SubmittedStatusRuntimeMemoryLanguage

01/22/2021 00:47 Accepted 32 ms 14.3 MB python3
01/22/2021 00:45 Runtime Error N/A N/A python3
01/22/2021 00:44 Runtime Error N/A N/A python3

 

반응형

댓글