LeetCode: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.


算法1

这道题首先想到的是动态规划, 字符串为s,设bool数组dp[i][j]表示子串s[i…j]是否可以完全匹配,那么动态规划方程如下:

  • 初始化dp数组为false
  • 如果dp[i+1][j-1] == true && s[i] == ‘(’&&s[j] == ‘)’或者 存在k = i+1…j-1 使得dp[i][k] == true && dp[k+1][j] = true ,则dp[i][j] = true

方程的意思是:要使子串s[i…j]能够完全匹配,那么有以下两种情况可以满足:a、子串s[i+1…j-1]完全匹配,且s[i]、s[j]是左右两个半括号;b、存在某个k,使得两个子串s[i…k]、s[k+1…j]都能完全匹配.

求得所有dp[i][j]后,最长匹配子串的长度 = max {j-i}, 其中 dp[i][j] = true;

下面代码中isValid相当于方程中的dp,注意到子串长度为奇数时,子串可能完全匹配。概算大时间复杂度为O(n^3),oj上大数据超时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class  Solution {
public :
     int  longestValidParentheses(string s) {
         const  int  len = s.size();
         bool  isValid[len][len];
         memset (isValid, 0, sizeof (isValid));
         int  res = 0;
         for ( int  i = 0; i < len-1; i++)
             if (s[i] == '('  && s[i+1] == ')' )
             {
                 isValid[i][i+1] = true ;
                 res = 2;
             }
         for ( int  k = 4; k <= len; k+=2) //k表示子串长度,只有长度为偶数的子串才可能是合法括号
             for ( int  i = 0; i <= len-k; i++) //i表示子串的起始位置
             {
                 if (isValid[i+1][i+k-2] && s[i] == '('  && s[i+k-1] == ')' )
                     isValid[i][i+k-1] = true ;
                 else
                 {
                     for ( int  j = i+1; j <= i+k-3; j++)
                         if (isValid[i][j] && isValid[j+1][i+k-1])
                             isValid[i][i+k-1] = true ;
                 }
                 if (isValid[i][i+k-1])res = k;
             }
         return  res;
     }
};

算法2

在处理括号匹配问题上,我们一般使用栈来解决。这一题也可以。

顺序扫描字符串:

初始化:在栈中压入-1

一、若碰到‘(’,则把当前位置压入栈中

二、若碰到‘)’:

     (1)、如果栈顶元素不是‘(’,则把当前位置压入栈中;

     (2)、如果栈顶元素时‘(’:栈顶元素出栈,当前的合法子串长度 = 当前字符索引 - 新的栈顶元素;更新最大子串长度

 

例如以下字符串

image

扫描到第0个字符‘(’时,0入栈

扫描到第1个字符‘)’时,栈顶对应字符为‘(’,把栈顶0出栈,当前合法子串长度 = 1 - 新的栈顶元素(-1) = 2;

扫描到第2个字符‘)’时,栈顶为-1,因此2入栈

扫描到第3个字符‘(’时,3入栈

扫描到第4个字符‘)’时,栈顶对应字符为‘(’,把栈顶3出栈,当前合法子串长度 = 4 - 新的栈顶元素(2) = 2;                                 本文地址

扫描到第5个字符‘(’时,5入栈

扫描到第6个字符‘)’时,栈顶对应字符为‘(’,把栈顶5出栈,当前合法子串长度 = 6 - 新的栈顶元素(2) = 4;

 

需要注意的是:当前合法子串当长度 != 当前索引 - 与当前的‘)’匹配的‘(’的索引 + 1, 例如扫描到第6个字符‘)’时,当前合法子串长度不是等于6-5+1 = 2,还要考虑到它前面已经匹配的3、4号位

 

算法时间空间复杂度都是O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class  Solution {
public :
     int  longestValidParentheses(string s) {
         const  int  len = s.size();
         stack< int > sta;
         int  res = 0;
         sta.push(-1); //为了处理边界条件,在栈底添加-1
         for ( int  i = 0; i < len; i++)
         {
             if (s[i] == '(' )
                 sta.push(i);
             else
             {
                 int  topIndex = sta.top();
                 if (topIndex >= 0 && s[topIndex] == '(' ) //s[i]可以和s[a]匹配
                 {
                     sta.pop();
                     if (res < i - sta.top())res = i - sta.top();
                 }
                 else  sta.push(i);
             }
         }
         return  res;
     }
};

 






本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3771122.html,如需转载请自行联系原作者

目录
相关文章
|
5月前
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
22 0
|
5月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters
此题题意是找出一个不包含相同字母的最长子串,题目给出了两个例子来说明题意,但这两个例子具有误导性,让你误以为字符串中只有小写字母。还好我是心机boy,我把大写字母的情况也给考虑进去了,不过。。。。字符串里竟然有特殊字符,于是贡献了一次wrong answer,这次我把ascii字符表都考虑进去,然后就没问题了。这个故事告诫我们在编程处理问题的时候一定要注意输入数据的范围,面试中可以和面试官去确认数据范围,也能显得你比较严谨。
27 3
LeetCode 424. Longest Repeating Character Replacem
给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
75 0
LeetCode 424. Longest Repeating Character Replacem
LeetCode 409. Longest Palindrome
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
53 0
LeetCode 409. Longest Palindrome
LeetCode 395. Longest Substring with At Least K
找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
57 0
LeetCode 395. Longest Substring with At Least K
|
Windows
LeetCode 388. Longest Absolute File Path
我们致力于寻找我们文件系统中文件的最长 (按字符的数量统计) 绝对路径。例如,在上述的第二个例子中,最长路径为 "dir/subdir2/subsubdir2/file2.ext",其长度为 32 (不包含双引号)。
51 0
LeetCode 388. Longest Absolute File Path
LeetCode 367. Valid Perfect Square
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
58 0
LeetCode 367. Valid Perfect Square
|
存储
LeetCode 329. Longest Increasing Path in a Matrix
给定一个整数矩阵,找出最长递增路径的长度。 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
45 0
LeetCode 329. Longest Increasing Path in a Matrix
LeetCode 301. Remove Invalid Parentheses
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含了除 ( 和 ) 以外的字符。
47 0
LeetCode 301. Remove Invalid Parentheses
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
34 0
LeetCode 300. Longest Increasing Subsequence