zoukankan      html  css  js  c++  java
  • 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.

    思路:DP。

    dp[i]记录最后一位是s[i]的最长合法串的长度。

    很明显,当s[i] = '('时dp[i] = 0。

    当s[i] = ')' 时,如果i不为0的话(为0肯定dp[i] = 0),则看一下dp[i - 1]记录的最长串的值。

    而i - 1 - dp[i - 1]就是最后一位是s[i - 1]的最长合法串的前面一个字符的位置。

    当dp[i - 1]等于0时,即没有合法串,该值正好是i - 1本身,而大于0时,则正好是合法串前面一位的下标。

    如果s[i - 1 - dp[i - 1]]是'('的话,就正好能和当前i位置的')'匹配,从而合法串长度等于dp[i - 1] + 2。

    但要注意一下,加入有如下情况,"()(())",当我们到了最后一位时,按照这个方法计算出的dp[i]=4,实际上应该为6,因为这样做忽略了前面还可能有能连起来的合法串。因此这里我们还要判断下i - 2 - dp[i - 1]是否大于等于0,如果是的话,则dp[i] = dp[i - 1] + 2 + dp[i - 2 - dp[i - 1]]。

     1 class Solution {
     2 public:
     3     int longestValidParentheses(string s) {
     4         int n = s.size(), res = 0;
     5         vector<int> dp(n, 0);
     6         for (int i = 1; i < n; i++)
     7         {
     8             if (s[i] == '(')
     9                 dp[i] = 0;
    10             else if (i - dp[i - 1] - 1 >= 0
    11                 && s[i - dp[i - 1] - 1] == '(')
    12                 dp[i] = dp[i - 1] + 2 + (i - dp[i - 1] - 2 >= 0 ?
    13                     dp[i - dp[i - 1] - 2] : 0);
    14             res = max(res, dp[i]);
    15         }
    16         return res;
    17     }
    18 };
  • 相关阅读:
    springMVC后端返回数据到前端
    spring MVC配置
    SSM框架中配置静态资源加载
    js实践问题收集日记
    页面HTml学习笔记
    js页面传值实践
    struts2中jsp页面与action之间的传值
    json与Java对象的转换
    JDBC的简单应用
    新的开始,重新启用博客园
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4925436.html
Copyright © 2011-2022 走看看