20. Valid Parentheses

来源:互联网 发布:乐高 t r3x 编程下载 编辑:程序博客网 时间:2024/06/05 16:35

Problem:

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.


Examples:

input: []()  output: true;

input: [()]  ouput: true;

input: [(    output: false;


这题是比较经典的栈问题,[{(都压栈,然后遇到)}]就开始匹配栈顶元素,只要不匹配则false。遍历string后,假如栈里还有元素,那么表示是缺失右元素,则false。其他情况则是true。


Code:

class Solution {public:    string stack = "";    bool isValid(string s) {        for (int i = 0; i < s.length(); i++) {            if (s[i] == '(' || s[i] == '{' || s[i] == '[') {                stack += s[i];            } else {                if (!isMatch(stack[stack.length() - 1], s[i])) {                    return false;                } else {                    stack.erase(stack.end()-1, stack.end());                }            }        }        if (stack.length() == 0) {            return true;        } else {            return false;        }    }    bool isMatch(char c1, char c2) {        if ((c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}') || (c1 == '[' && c2 == ']')) {            return true;        }        return false;    }};


原创粉丝点击