Fork me on GitHub

【LeetCode】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.

提示:

此题借助于“栈”这一数据结构,可以较方便的实现题目的要求

代码:

class Solution {
public:
    bool isValid(string s) {
        if (s.size() == 0) return true;
        stack<char> bracket_stack;
        int i = 0;
        while (i < s.size()) {
            if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
                bracket_stack.push(s[i++]);
            }else {
                if (!bracket_stack.empty() && (s[i] == ')' && bracket_stack.top() == '(' ||
                    s[i] == '}' && bracket_stack.top() == '{' ||
                    s[i] == ']' && bracket_stack.top() == '[')) {
                        bracket_stack.pop();
                        ++i;
                } else {
                    return false;
                }
            }
        }
        if (!bracket_stack.empty()) return false;
        return true;
    }
};
posted @ 2015-08-25 15:43  __Neo  阅读(111)  评论(0编辑  收藏  举报