Leetcode 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.

 
思路:利用栈,如果是左括号,则放入右括号,如果是右括号,则跟最近的左括号对比,也就是跟栈顶对比,配对则继续,不配对或者栈空了,则不合法。
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        int n=s.size();
        if(n%2!=0)
            return false;
        for(int i=0;i<n;++i)
        {
            if(s[i]=='(')
                st.push(')');
            else if(s[i]=='[')
                st.push(']');
            else if(s[i]=='{')
                st.push('}');
            else if(st.empty()||st.top()!=s[i])
                return false;
            else
                st.pop();
        }
        if(st.empty()) return true;
        return false;
    }
};
原文地址:https://www.cnblogs.com/zl1991/p/12783638.html