Stack

20. 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> str;
        for(auto c:s){
            if(c=='('||c=='{'||c=='[')
                str.push(c);
            else if(c==')'||c=='}'||c==']'){
                if(str.empty()) return false;
                char top=str.top();
                if(top=='('&&c==')' || top=='['&&c==']' || top=='{'&&c=='}') str.pop();
                    else return false;
            }else return false;
        }
        return str.empty();
    }
};

32. Longest Valid Parentheses


Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

最长合法括号对,题目标签是动态规划,但是这类括号匹配的问题用栈做也比较简单。思路一般是遇到左括号入栈,遇到右括号时,若栈不为空则弹出栈顶,并实时更新合法串长;若栈为空则更新合法串起始位置为当前位置。

class Solution {
public:
    int longestValidParentheses(string s) {
        int maxLen=0;
        int last=-1;
        vector<int> stack;
        for(int i=0;i<s.size();i++){
            if(s[i]=='('){
                stack.push_back(i);
            }else if(s[i]==')'){
                if(stack.size()>0){
                    stack.pop_back();
                    int len;
                    if(stack.size()==0){
                        len=i-last;
                    }else{
                        len=i-stack.back();
                    }
                    if(len>maxLen){
                        maxLen=len;
                    }
                }else{
                    last=i;
                }
            }
        }
        return maxLen;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值