Valid Parentheses--LeetCode

来源:互联网 发布:淘宝哪家鞋子质量好 编辑:程序博客网 时间:2024/05/10 21:15

1.题目

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.

2.题意

括号匹配

3.分析

利用栈后进先出的特点即可
时间复杂度为O(n),空间复杂度也为O(n)
注意一开始是要先让左括号入栈而非判断栈是否为空
if(s[i] == ']' && parentheses.top() != '[')使用&&而非||不要写错

4.代码

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