반응형
https://leetcode.com/problems/valid-parentheses/
Leetcode 20 - Valid Parentheses
문제 설명
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.
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 '()[]{}'.
문제 풀이
class Solution {
public:
bool isValid(string s) {
stack<int> st;
for (auto c : s)
{
if (c == '(' || c == '{' || c == '[')
{
st.push(c);
}
if (st.size() == 0)
return false;
if (c == ')')
{
if (st.top() == '(')
st.pop();
else
return false;
}
if (c == '}')
{
if (st.top() == '{')
st.pop();
else
return false;
}
if (c == ']')
{
if (st.top() == '[')
st.pop();
else
return false;
}
}
if (st.empty())
return true;
else
return false;
}
};
반응형
'개발 > 알고리즘 & 자료구조' 카테고리의 다른 글
BOJ 1662 - 압축 (C++) (0) | 2021.10.04 |
---|---|
BOJ 14719 - 빗물 (C++) (1) | 2021.10.03 |
BO 15657 - N과 M (8) (0) | 2021.09.28 |
BOJ 12865 - 평범한 배낭 (C++) (0) | 2021.09.27 |
BOJ 17219 - 비밀번호 찾기 (C++) (0) | 2021.09.26 |