题目:

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的更多相关文章

  1. 【Valid Parentheses】cpp

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  2. 【Longest Common Prefix】cpp

    题目: Write a function to find the longest common prefix string amongst an array of strings. 代码: class ...

  3. 【Longest Palindromic Substring】cpp

    题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...

  4. 【Longest Consecutive Sequence】cpp

    题目: Given an unsorted array of integers, find the length of the longest consecutive elements sequenc ...

  5. 【leetcode】Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  6. 【leetcode】 Longest Valid Parentheses (hard)★

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. 【LeetCode练习题】Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  8. 【Python】32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  9. 【一天一道LeetCode】#32. Longest Valid Parentheses

    一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...

随机推荐

  1. 字符串匹配KMP算法

    1. 字符串匹配的KMP算法 2. KMP算法详解 3. 从头到尾彻底理解KMP

  2. jQuery插件Skippr实现焦点图

    史上效果最好的焦点图幻灯片jQuery插件Skippr,轻量级插件.响应式布局插件,强大的参数自定义 配置,可自定义切换速度.切换方式.是否显示左右箭头.是否自动播放.自动播放间隔时间等配置 参数,调 ...

  3. 兼容firefox的iframe高度自适应代码

    网上关于iframe高度自适应的代码有很多,但比较杂乱,本文根据实用性整理了以下代码: JavaScript部分: 折叠JavaScript Code复制内容到剪贴板 <script type= ...

  4. GridView 鼠标经过时变色两种方法

    第一种: 新建一个js文件 并引用 <script src="jquery.js" type="text/javascript"></scri ...

  5. C# .Net三层架构[转]

    C# .Net三层架构[转] 编写人:CC阿爸 2014-3-14 希望朋友们留下自己对三层架构的理解... 三层体系结构的概念     用户界面表示层(USL) 业务逻辑层(BLL) 数据访问层(D ...

  6. Android照相机应用

    前言 Android在设计架构的时候,采用了mashup(混搭)的设计理念,也就是说一切都是组建,自己写的是组件,别人提供的也是组件,使用的时候只要符合相关协议就可以把他们当作自己的组件.比如系统提供 ...

  7. Oracle 10g 之自动收集统计信息

    从10g开始,Oracle在建库后就默认创建了一个名为GATHER_STATS_JOB的定时任务,用于自动收集CBO的统计信息.这个自动任务默认情况下在工作日晚上10:00-6:00和周末全天开启. ...

  8. nandflash操作详解

    1.nandflash就是嵌入式系统的硬盘 2.分类(1)MLC:存储单元格存储两位,慢,偏移,寿命短,容量大(2)SLC:存储一位.快,寿命长,容量小,昂贵 3访问:(1)独立编址,有专用的控制器, ...

  9. 小心C语言的定义与声明

    小心C语言的定义与声明 转自360博客 注:为便于说明问题,文中提及的变量和函数都被简化. 一.起源 DBProxy在测试过程中,发现对其执行某步管理操作后,程序有时会崩溃,但不是每次都出现. 二.G ...

  10. eth0: error fetching interface information: Device not found

    转载,原文出处:http://zh888.blog.51cto.com/1684752/775447 亲测有效,感谢作者!!! ----------------------------分割线----- ...