티스토리 뷰

PS

leetcode) #20) Valid Parentheses

tose33 2021. 2. 22. 18:06

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

 

스택사용

 

ool isValid(string s) {
    stack<char> st;
    int len = s.size();

    st.push(s[0]);
    for(int i = 1; i < len; i++) {
        // if it's closing
        if(s[i] == ')') {
            if(st.empty() || st.top() != '(') return false;
            if(st.top() == '(') st.pop();
        }
        else if(s[i] == ']') {
            if(st.empty() || st.top() != '[') return false;
            if(st.top() == '[') st.pop();
        }
        else if(s[i] == '}') {
            if(st.empty() || st.top() != '{') return false;
            if(st.top() == '{') st.pop();
        }
        else { // opening
            st.push(s[i]);
        }
    }

    if(st.empty()) return true;
    else return false;

}

 

'PS' 카테고리의 다른 글

백준 10844. 쉬운 계단 수  (0) 2021.03.01
leetcode) #53. Maximum Subarray  (0) 2021.02.22
leetcode) #3. Longest Substring Without Repeating Characters  (0) 2021.02.19
leetcode) #1. Two sum  (0) 2021.02.18
leetcode와 백준  (0) 2021.02.17
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함