题目:

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. 利用jQuery获取鼠标当前的坐标

    文字来源:http://www.smalluv.com/jquery_code_106.html jQuery获取当前鼠标坐标位置: <div id="testDiv"> ...

  2. 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(七)-- 结构化配置

    本篇将记录.Net Core里颇有特色的结构化配置的使用方法. 相比较之前通过Web.Config或者App.Config配置文件里使用xml节点定义配置内容的方式,.Net Core在配置系统上发生 ...

  3. PHP用Array模拟枚举

    C#中枚举Enum的写法: /// <summary> /// 公开类型 2-好友可见 1-公开 0-不公开 /// </summary> public enum OpenSt ...

  4. 理解 JavaScript Scoping & Hoisting(二)

    理解 JavaScript Scoping & Hoisting(二) 转自:http://www.jb51.net/article/75090.htm 这篇文章主要介绍了理解 JavaScr ...

  5. 使用maven, myeclipse工具构建spring mvc项目

    一.使用myeclipse 创建一个新的 maven项目. (ps:1.在filter过滤的时候输入 webapp 选择"maven-archetype-webapp". 2.在m ...

  6. 神奇的fastcgi_finish_request

    当PHP运行在FastCGI模式时,PHP FPM提供了一个名为fastcgi_finish_request的方法.按照文档上的说法,此方法可以提高请求的处理速度,如果有些处理可以在页面生成完后再进行 ...

  7. 2013/8/28 JS+HTML 三级省市区联动

    var mp = ["安徽","北京","福建","甘肃","广东","广西", ...

  8. ASP.NET MVC5学习笔记之Action参数模型绑定之模型元数据和元数据提供

    一. 元数据描述类型ModelMetadata 模型元数据是对Model的描述信息,在ASP.NET MVC框架中有非常重要的作用,在模型绑定,模型验证,模型呈现等许多地方都有它的身影.描述Model ...

  9. Laravel 5 基础(七)- Eloquent (laravel 的ORM)

    我们来生成第一个模型 php artisan make:model Article #输出 Model created successfully. Created Migration: 2015_03 ...

  10. linux kernel 0.11 head

    head的作用 注意:bootsect和setup汇编采用intel的汇编风格,而在head中,此时已经进入32位保护模式,汇编的采用的AT&T的汇编语言,编译器当然也就变成对应的编译和连接器 ...