20. Valid Parentheses

来源:互联网 发布:知乎日报web电脑版 编辑:程序博客网 时间:2024/04/29 09:29

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) {        stack<char> stack;        for(int i = 0; i < s.size(); i++)        {            if(s[i] == '(' || s[i] == '[' || s[i] == '{')            {                stack.push(s[i]);            }            else            {                if(!stack.empty() && checkValid(stack.top(),s[i]))                {                    stack.pop();                }                else                {                    return false;                }            }        }        return stack.empty();    }    bool checkValid(char c1, char c2)    {         return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')            || (c1 == '[' && c2 == ']');    }};
0 0