leetcode 32:Longest Valid Parentheses
2015-10-17 15:57
453 查看
题目:
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
思路:
这题存在最优子结构,即如果前面子字符串的是有效的,则后面的有效字符串包括前面的部分。
我们可以用一个数组DP来存储每个单括号对应的有效括号个数,则有下面的关系:
事件复杂度:O(n)
class Solution
{
public:
int longestValidParentheses(string s)
{
int size=s.size();
if(size<2) return 0;
int left=0,max=0;
vector<int> DP(size,0);
for(int i=0;i<size;i++)
{
if(s[i]=='(') left++;
else if(left>0)
{
left--;
if(s[i-1]=='(')
DP[i]=((i-2)>0?DP[i-2]+2:2);
else if(s[i-1]==')'&&s[i-DP[i-1]-1]=='(')
DP[i]=DP[i-1]+2+((i-DP[i-1]-2)>=0?DP[i-DP[i-1]-2]:0);
}
if(DP[i]>max) max=DP[i];
}
return max;
}
};
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来存储每个单括号对应的有效括号个数,则有下面的关系:
事件复杂度:O(n)
class Solution
{
public:
int longestValidParentheses(string s)
{
int size=s.size();
if(size<2) return 0;
int left=0,max=0;
vector<int> DP(size,0);
for(int i=0;i<size;i++)
{
if(s[i]=='(') left++;
else if(left>0)
{
left--;
if(s[i-1]=='(')
DP[i]=((i-2)>0?DP[i-2]+2:2);
else if(s[i-1]==')'&&s[i-DP[i-1]-1]=='(')
DP[i]=DP[i-1]+2+((i-DP[i-1]-2)>=0?DP[i-DP[i-1]-2]:0);
}
if(DP[i]>max) max=DP[i];
}
return max;
}
};
相关文章推荐
- spring mvc 读取绝对路径地址,显示出来
- prototype.js 和 jQuery.js中 ajax 的使用
- 旅行售货员问题
- cnetos 配置163-epel-zabbix 源
- 【自考】门卫思维体现的知识网—软件开发工具
- 【自考】门卫思维体现的知识网—软件开发工具
- 《大道至简》第三章读后感
- 大道至简第三章读后感
- android 30 下拉列表框:ArrayAdapter和Spinner.
- SeaJS实例小动画
- C/C++面试(2)——const
- 读《认知与设计:理解UI设计准则》第二章
- Cuda 编程小知识点积累————持续更新
- ioS开发之c语言基础-一维数组,字符数组
- javascript 中的apply()和call()方法详解
- 创建并使用Linux 桌面启动器(.Desktop文件)
- Android完全高仿58同城 点击展开的表格效果
- Android线程浅析
- 大型门户站内页如何优化最好
- 第三次作业