leetcode习题解答:32. Longest Valid Parentheses

难度:Hard

链接

描述:

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.



思路:之前做了个生成有效的括号串的题,最开始想用左右括号的数量关系来解决,想了半天,没效果,因为光凭数量关系是很难区分有效子串是否连在一起,放弃了。

之后决定使用这个方法:把不符合规则的字符替换为空格,这样就能得出,一堆子串,再比较他们长度就行。

那怎么做到呢?可以使用栈来实现,对于左括号,将其index入栈,遇到右括号,就出栈,当栈空时遇到右括号,可以直接判断这个右括号是无效的。

最终栈中剩下的index,则是无效左括号的index,将它们全部赋值为空格。

最后扫描整个字符串,得出最长有效子串,完成。

代码:

#include <vector>
class Solution {
public:
    int longestValidParentheses(string s) {
        std::vector<int> wl;    //use vector as a stack
        
        int l = 0;           
        for (int i = 0; i < s.size(); i++){
            if (s[i] == ')' && l == 0){
                s[i] = ' ';
            } else if (s[i] == ')' && l != 0){
                wl.pop_back();
                l--;
            } else if (s[i] == '('){
                wl.push_back(i);
                l++;
            }
        }
        for (int i = 0; i < wl.size(); i++){
            s[wl[i]] = ' ';
        }
        int max = 0;
        int temp = 0;
        for (int i = 0; i < s.size(); i++){
            if (s[i] != ' '){
                temp++;
            } else {
                if (temp > max) max = temp;
                temp = 0;
            }
        }
        if (temp > max) return temp;
        else return max;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值