ITPub博客

首页 > > > [LeetCode] Longest Valid Parentheses

[LeetCode] Longest Valid Parentheses

作者:Ruiyuan Li 时间:2015-04-29 00:00:00 0 删除 编辑

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.

解题思路:

题意找到最长有效括号的子串长度。求最大问题,第一想法就是动态规划,但是,通项公式真不好找。喜刷刷http://bangbingsyb.blogspot.jp/2014/11/leetcode-longest-valid-parentheses.html中有相关说明,我没有理解,大哭。

由于是括号问题,可以用栈来实现。这跟判断栈是否有效不同。注意到,若某个右括号不与前面的某个左括号匹配,那么,这个右括号可以作为子串分割标记。大体思想是,若遇到左括号,无条件将左括号的下标入栈。若遇到右括号,若栈顶是左括号与之匹配,将左括号出栈,更新最大的长度值。若栈顶没有左括号与之匹配,将该右括号的下标入栈,作为分割字符。代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        int len=s.length();
        
        stack st;
        
        int maxLen=0;
        
        for(int i=0; i


<!-- -->

原文作者:;如有侵权,请联系管理员删除。

上一篇: R vs Python(转)
下一篇: Windows 远程登录
请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825