본문 바로가기
IT/LeetCode

[LeetCode] 20. Valid Parentheses

by 강천구 2022. 7. 21.

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

 

Constraints:

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

주어진 소, 중, 대괄호로 이루어진 문자열이 알맞게 짝이 이룬 여부를 확인하는 문제이다.

일단 글자 수가 홀수이면 False를 출력하며, 0은 True로 일부분 걸러낸다.

그 후  While문을 통해 소, 중, 대괄호가 짝지어진 곳을 찾아 제거하며 존재하지 않을 때까지 반복한다.

 

class Solution:
   def isValid(self, s):
       n = len(s)
       if n == 0:
           return True

       if n % 2 != 0:
           return False

       while '()' in s or '{}' in s or '[]' in s:
           s = s.replace('{}','').replace('()','').replace('[]','')

       if s == '':
           return True
       else:
           return False

 

문제 출처 : https://leetcode.com/problems/valid-parentheses/

 

Valid Parentheses - 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

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_20.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

댓글