코딩테스트 준비/leetcode
20. Valid Parentheses
MAKGA
2021. 9. 21. 21:45
320x100
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
(){}[]로 구성되어있는 문자열이 괄호쌍이 순서대로 열리고 닫혀있는지 확인하는 문제다.
처음엔 순서쌍 갯수만 맞으면 되는줄 알고 counting만 했어야 했는데, 열리고 닫히는 순서도 체크해야해서 stack 으로 변경해서 풀었다.
class Solution {
public:
bool checkfunc(stack<char>& stack_, char c) {
if (stack_.empty())
return false;
if (c != stack_.top())
return false;
stack_.pop();
return true;
}
bool isValid(string s) {
stack<char> stack_;
for (char c : s) {
switch(c)
{
case ')': {
if (!checkfunc(stack_, '('))
return false;
break;
}
case '}': {
if (!checkfunc(stack_, '{'))
return false;
break;
}
case ']': {
if (!checkfunc(stack_, '['))
return false;
break;
}
default : stack_.push(c); break;
}
}
return stack_.empty();
}
};
320x100