LeetCode20. Valid Parentheses

来源:互联网 发布:电缆设备负荷计算软件 编辑:程序博客网 时间:2024/06/06 08:42

原题:https://leetcode.com/problems/valid-parentheses/description/


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.


用1,2,3代表三种括号
用一个栈存储左括号,栈顶就是最近的一个左括号,每次遇到右括号时,和栈顶比对,如果匹配则将栈顶pop。如果遇到右括号时栈已空则返回False,匹配完之后栈不为空也返回False。


class Solution {public:    bool isValid(string s) {        stack<int> last;        for (int i = 0; i < s.size(); i++) {            if (s[i] == '(') last.push(1);            if (s[i] == '[') last.push(2);            if (s[i] == '{') last.push(3);            if (s[i] == ')') {                if (last.empty()||last.top() != 1) {                    return false;                }                last.pop();            }            if (s[i] == ']') {                if (last.empty()||last.top() != 2) {                    return false;                }                last.pop();            }if (s[i] == '}') {                if (last.empty()||last.top() != 3) {                    return false;                }                last.pop();            }        }        return last.empty();    }};

73 / 73 test cases passed.
Status: Accepted
Runtime: 3 ms

原创粉丝点击