2017-09-10 LeetCode_020 Valid Parentheses

20. Valid Parentheses

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.

Solution:
#include <stack>
2
class Solution {
3
public:
4
    bool isValid(string s) {
5
        int to[256] = {0};
6
        for (int i = 0; i < 256; i++) to[i] = -1;
7
        to['{'] = '}'; to['['] = ']'; to['('] = ')';
8
        stack<int> sta;
9
        for (int i = 0; i < s.length(); i++) {
10
            if (sta.size() && to[sta.top()] == s[i]) sta.pop();
11
            else sta.push(s[i]);
12
        }
13
        return sta.empty();
14
    }
15
};




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