20. Valid Parentheses

来源:互联网 发布:网络盒子加密软件 编辑:程序博客网 时间:2024/06/05 21:03

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.

题目要求判断括号是否匹配,可以用栈来做。
stl stack的用法:http://www.cplusplus.com/reference/stack/stack/

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()) return false;                if ((s[i] == ')' && stack.top() == '(') ||                    (s[i] == ']' && stack.top() == '[') ||                    (s[i] == '}' && stack.top() == '{'))                    stack.pop();                else return false;            }        }        return stack.empty();    }};
原创粉丝点击