LeetCode 20. Valid Parentheses

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Analysis

典型的棧結構應用。

Code

class Solution {
public:
    bool isValid(string s) {
        stack<char> t;
        for (char c : s){
            if (c == '(' || c == '{' || c == '[')
                t.push(c);
            else
                switch (c){
                    case ')':
                        if (!t.empty() && t.top() == '(')
                            t.pop();
                        else return false;
                        break;
                    case '}':
                        if (!t.empty() && t.top() == '{')
                            t.pop();
                        else return false;
                        break;
                    case ']':
                        if (!t.empty() && t.top() == '[')
                            t.pop();
                        else return false;
                        break;
                    default:
                       return false;
                }
        }
        if (t.empty())
            return true;
        else return false;
    }
};

Appendix

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章