题目:

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. ADO.NET中的Connection详解

    连接字符串 1.写法一 "Data Source=服务器名; Initial Catalog=数据库; User ID =用户名; Password=密码; Charset=UTF8; &q ...

  2. 举例详解CSS中的继承

    CSS的继承是由所使用的样式属性定义的.换句话说,当你查看CSS属性backgruound-color,你会看到一栏「继承性」,也许你几乎没有在意过它,但是它还是十分有用的.什么是CSS继承 每一个元 ...

  3. 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(六)-- 依赖注入

    本篇将介绍Asp.Net Core中一个非常重要的特性:依赖注入,并展示其简单用法. 第一部分.概念介绍 Dependency Injection:又称依赖注入,简称DI.在以前的开发方式中,层与层之 ...

  4. (转载)前端构建工具gulp使用

    前端构建工具gulp使用 前端自动化流程工具,用来合并文件,压缩等. Gulp官网 http://gulpjs.com/ Gulp中文网 http://www.gulpjs.com.cn/ Gulp中 ...

  5. highcharts与highstock实例

    highcharts实例代码 <head> <title>highcharts报表示例</title> <meta http-equiv="Cont ...

  6. Lambda Grinding Miller From Zenith

    data = """ The Basic Things About Grinding Mill A grinding mill is a unit operation d ...

  7. 使用了Theme但是没有效果问题

    最近在开发过程中使用了theme移植Preference并使用了一些android样式,但是在自定义的Theme修改了相关参数后却无法实现 可能有些朋友还不知道怎么用.这里也做个简要的使用方式说明. ...

  8. sql server 跨库操作

    SELECT *FROM OPENDATASOURCE('SQLOLEDB','Data Source=sql服务器名;User ID=用户名;Password=密码;').PersonDb.dbo. ...

  9. linux之I2C裸机驱动解析(转)

    1      硬件特性 1.1 概述 I2C总线是由Philips公司开发的两线式串行总线,这两根线为时钟线(SCL)和双向数据线(SDA).由于I2C总线仅需要两根线,因此在电路板上占用的空间更少, ...

  10. Python学习教程(learning Python)--1.4 Python数据处理基础

    本节主要讨论数据操作及运算符等基础知识,熟悉C语言相关知识的读者请跳过此节. 在高级语言编程过程中,有了数据以后通常要对数据进行相应的数据处理,加.减.乘.除等基本运算,不难理解. 在Python里 ...