题目:

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. Eclipse 中打不开android sdk managerf

    今天配置android sdk 的时候,出现了android sdk 打不开的情况.无论直接点击 sdk manager.exe 还是从eclipse启动,都不起作用,双重启(重启eclipse和ad ...

  2. .NET中 使用数组的注意事项

    1.初始值问题 对于int.double.float等一些值类型数组,没有赋值的情况下, 默认值是0: 而对于String 等引用类型,初始值为null. 2.IndexOutOfRangeExcep ...

  3. 树莓派(Rospberry Pi B+)到货亲测

    1 图鉴 Rospberry Pi  B+终于在今天下午有蜗牛快递公司圆*送到了.B+主要是增加了2个USB,增加了GPIO,sd卡换成了micro sd ...先不说直接上图再说,期待了好久好久 整 ...

  4. 首页banner特效

     <link href="css/swiper.min.css" rel="stylesheet" />  <script src=" ...

  5. Jquery数组操作技巧

    Jquery对数组的操作技巧. 1. $.each(array, [callback]) 遍历[常用]  解释: 不同于例遍 jQuery 对象的 $.each() 方法,此方法可用于例遍任何对象(不 ...

  6. delphi 更改不了窗体的标题

    delphi定义变量名千万要注意,不能和关键字同名,今天我无意间定义了一个caption的变量  导致我怎么都不能修改窗的标题.

  7. delphi 基础之三 编写和调用dll文件

    delphi 编写和调用dll文件   Windows 的执行文件可以划分为两种形式程序和动态连接库 (DLLs).一般程序运行是用.EXE文件,但应用程序有时也可以调用存储在DLL的函数. 在如下几 ...

  8. Mysql 简单问题汇总(持续更新)

    主从架构相关问题 问题现象:从机连接主机时报错 [ERROR] Slave I/O: error connecting to master 'repl@192.168.0.50:3306' - ret ...

  9. 263. Ugly Number

    Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers ...

  10. SQLserver使用映射表进行数据相关操作

    基本需求: 老数据有老数据的顺序编码规则,新数据有新数据的顺序编码规则,但是老数据的编码还是要更新相应的东西,新数据也得实时更新,在新数据中已经用新编码规则对老数据对进行编码,在上报表中既要新增新数据 ...