-
[LeetCode] 20. Valid ParenthesesLeetCode 2021. 11. 9. 17:07728x90
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
Valid Parentheses - Easy

괄호들이 순서대로 열리고 닫혔는지 판단하는 문제.
stack을 만들어 여는 괄호가 나오면 닫는 괄호를 stack에 넣어준다.
닫는 괄호가 나오면 stack의 사이즈를 체크한뒤 stack의 top이 그 괄호와 같은지 체크한다.
사이즈가 있고 같다면 pop() 을해주고, 아니라면 바로 false를 리턴한다.
마무리가 되면
stack이 비어있는지 확인하여 비어있으면 true, 아니라면 false를 리턴한다.
전체 풀이 코드
class Solution { public: bool isValid(string s) { stack<char> st; for (char c:s) { if (c=='(') st.push(')'); else if (c=='{') st.push('}'); else if (c=='[') st.push(']'); else if (st.size() && c==st.top()) st.pop(); else return false; } return st.empty(); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 781. Rabbits in Forest (0) 2021.11.10 [LeetCode] 1773. Count Items Matching a Rule (0) 2021.11.09 [LeetCode] 1302. Deepest Leaves Sum (0) 2021.11.09 [LeetCode] 1178. Number of Valid Words for Each Puzzle (0) 2021.11.09 [LeetCode] 96. Unique Binary Search Trees (0) 2021.11.08