개발자도전
[LeetCode] 20. Valid Parentheses 본문
728x90
[문제]
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
'(', ')', '{', '}', '[' , ']' 괄호로 이루어진 문자열이 해당 조건을 만족하면 true를 만족하지 않으면 false를 반환.
- 열린 괄호와 동일한 괄호로 닫혀있는가
- 괄호는 올바른 순서로 닫아야함.
- 모든 닫힌 괄호에는 맞는 열린 괄호가 있음.
[입출력 예]
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
[답]

stack을 이용해서 문제를 풀었다.
6번째 줄에서 문자열 s의 길이가 홀수라면 괄호가 짝을 이룰 수 없어서 false를 반환시켜주었다.
10번째 줄에서 for문을 사용하여 s의 i번째 문자를 bracket에 저장해주었다.
14번째 줄에서 if 문을 사용해서 저장한 bracket이 '(', '[', '{'로 시작하면 stack에 저장하도록 해주었고
그 외의 경우는 닫힌 괄호로 시작한다는 뜻이니 먼저 stack이 비어있지 않다면 시작괄호가 저장되어있다는 뜻이니
닫힌괄호와 비교해서 값을 return 시켜주었다.
for문이 끝난 후에도 stack이 비어있는지 검사해서 값을 return 시켜주었다.
728x90
'LeetCode' 카테고리의 다른 글
| [LeetCode] 66. Plus One (0) | 2023.02.06 |
|---|---|
| [LeetCode] 58. Length of Last Word (0) | 2023.02.02 |
| [LeetCode] 35. Search Insert Position - java (0) | 2023.02.01 |
| [LeetCode] Valid Mountain Array (0) | 2023.01.31 |
| [LeetCode] Check If N and Its Double Exist (0) | 2023.01.28 |
Comments