2017-09-10 LeetCode_020 Valid Parentheses

来源:互联网 发布:dnf淘宝买金币安全吗 编辑:程序博客网 时间:2024/05/29 09:03

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
};



原创粉丝点击