leetcode 032 —— Longest Valid Parentheses
2015-07-14 21:30
459 查看
Given a string containing just the characters
find the length of the longest valid (well-formed) parentheses substring.
For
which has length = 2.
Another example is
is
思路:普通求解会超时,采用动态规划,动态数组d[i] 表示从i开始的最长有效字符串
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
int *d = new int
;
int max=0;
for (int i = 0; i < n; i++)
d[i] = 0;
for (int i = n - 2; i >= 0; i--){
if (s[i] == '('){
int j = i + 1 + d[i + 1];
if (j<n&&s[j] == ')'){
d[i] = d[i + 1] + 2;
if (j + 1 < n){
d[i] += d[j + 1];
}
}
max = max > d[i] ? max : d[i];
}
}
return max;
}
}a;
'('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.
思路:普通求解会超时,采用动态规划,动态数组d[i] 表示从i开始的最长有效字符串
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
int *d = new int
;
int max=0;
for (int i = 0; i < n; i++)
d[i] = 0;
for (int i = n - 2; i >= 0; i--){
if (s[i] == '('){
int j = i + 1 + d[i + 1];
if (j<n&&s[j] == ')'){
d[i] = d[i + 1] + 2;
if (j + 1 < n){
d[i] += d[j + 1];
}
}
max = max > d[i] ? max : d[i];
}
}
return max;
}
}a;
相关文章推荐
- 读《JavaScript高级程序设计》
- lpc1114的spi速率设置
- 全局变量和局部变量
- mysql字段特定值排序实现方式
- 关于一个数组中两个数的和等于给定数的问题
- 关于del命令
- 06 变量和引用
- CC1101 433无线模块,STM8串口透传
- 我的博客
- K能
- 贪心 模拟
- Android 模拟器错误PANIC: Could not open XXX
- leetcode--TWO SUM延伸(假设答案不唯一、假设输入有相同数字)
- 毕业论文经验
- C和C#的区别
- Code Forces 448C Painting Fence 贪婪的递归
- CDOJ 631 敢说敢做 记忆化搜索and动规
- [leedcode 78] Subsets
- OC相关基础知识3
- POJ 题目1364 King(差分约束)