【Longest Valid Parentheses】cpp
题目:
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.
代码:
class Solution {
public:
int longestValidParentheses(string s) {
int global_longest = ;
int last_not_match = -;
stack<int> sta;
for ( int i = ; i < s.length(); ++i )
{
if ( s[i]=='(')
{
sta.push(i);
continue;
}
if ( s[i]==')')
{
if ( sta.empty() )
{
last_not_match = i;
}
else
{
sta.pop();
if ( sta.empty() )
{
global_longest = std::max( global_longest, i-last_not_match );
}
else
{
global_longest = std::max( global_longest, i-sta.top() );
}
}
}
}
return global_longest;
}
};
tips:
这里巧用堆栈,核心是堆栈里存放的不是字符本身而是字符所在的索引值。
额外再用一个变量保存上一次没有匹配的字符的索引值。
每次更新global_longest的时候,都判断堆栈是否清空:
1. 如果堆栈清空了,则证明直到last_not_match之前的都是有效的字符串,所以完整有效长度为i-last_not_match
2. 如果堆栈没有清空,则说明还有‘(’没有被匹配上,所以临时有效长度i-sta.top()
这里设定last_not_match初始值为-1,主要是考虑如果从第一个元素就包含在有效范围内的test case (如,“()”)
=======================================
此题还有DP的解法,但总感觉DP解法思路不太直观,怪怪的。
留一个看过的DP解法的blog,以后有时间再研究
http://bangbingsyb.blogspot.sg/2014/11/leetcode-longest-valid-parentheses.html
=========================================
第二次过这道题,一开始写了一个动态规划的算法:逻辑可能是对的,但是绝对超时。
还是强化记忆了一下stack的做法:巧用栈的特点,O(n)复杂度搞定。
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> sta;
int ret = ;
int last_not_match = -;
int i=;
while ( i<s.size() )
{
if ( s[i]=='(' )
{
sta.push(i);
}
else
{
if ( sta.empty() )
{
last_not_match = i;
}
else
{
sta.pop();
if (sta.empty())
{
ret = max(ret,i - last_not_match);
}
else
{
ret = max(ret, i - sta.top());
}
}
}
++i;
}
return ret;
}
};
【Longest Valid Parentheses】cpp的更多相关文章
- 【Valid Parentheses】cpp
题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...
- 【Longest Common Prefix】cpp
题目: Write a function to find the longest common prefix string amongst an array of strings. 代码: class ...
- 【Longest Palindromic Substring】cpp
题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...
- 【Longest Consecutive Sequence】cpp
题目: Given an unsorted array of integers, find the length of the longest consecutive elements sequenc ...
- 【leetcode】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- 【leetcode】 Longest Valid Parentheses (hard)★
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【LeetCode练习题】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- 【Python】32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【一天一道LeetCode】#32. Longest Valid Parentheses
一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...
随机推荐
- 学习c的第7天
#include <stdio.h> int main() { int x=0; if (x==0) { printf("x为假\n"); } else { print ...
- centos查看设置端口开放状态
centos查看端口是否已开放/etc/init.d/iptables status centos开放端口/sbin/iptables -I INPUT -p tcp --dport 8000 -j ...
- Linux 服务器如何设置文件和文件夹的读写权限
修改文件可读写属性的方法 例如:把index.htm 文件修改为可写可读可执行: chmod 777 index.htm 要修改目录下所有文件属性可写可读可执行: chmod 777 *.* 该命令中 ...
- JS获取网页属性包括宽、高等
JS获取网页属性包括宽.高等. function getInfo() { // www.jbxue.com var s = ""; s += " 网页可见区域宽:&q ...
- (转)浅谈HTML5与css3画饼图!
神马系饼图? 饼图,大家都应该熟知,在统计数据对比方面,几乎处处用到.如cnzz的统计饼图 从饼图中,很形象地展示了访问者地区的分布,以扇形为块的方式拼成一个大圆. 都使用什么方法实现 目前众多站点制 ...
- (原创)Windows8下安装配置WAMP
Windows8下安装配置WAMP 2013/12/28 最近这段时间一直在研究linuxshell编程,虽然还是初级水平,但比之前有了不小的进度,但是shell的命令很多,很难在短时间 ...
- PHP取当前页面完整URL地址
#测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br> ...
- delphi中的ClientDataSet组件的open和Execute方法各自在什么情况下用?
ClientDataSet组件本来是给midas用的,也是所谓的borland的三层数据技术,使用这个控件必须发行midas.dll挺麻烦的 open是通过应用的SQL语句为SELECTexecute ...
- Java 打印金字塔 or 打印带数字的金字塔 (Java 学习中的小记录)
Java 打印金字塔 or 打印带数字的金字塔 (Java 学习中的小记录) 作者:王可利(Star·星星) 效果图: 代码如下: class Star8 { public static void m ...
- Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string. Example 1:Giv ...