题目:

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中的DataSet和DataAdapter

    DataSet和DataTable DataSet是一个数据集合,存储在内存中,算是一个临时的数据库. 个人觉得,不是太常用了,DataTable或者直接用List<model>存数据比这 ...

  2. 必须会的SQL语句(二) 创建表、修改表结构、删除表

    1.创建数据库表 --使用哪个数据库,如果不写这一句是默认的数据库,也可以用鼠标选当前数据库 use testDB --创建表    Create Table tablename    (       ...

  3. 如何在某个按钮上触发 bootstarp Modal 组件

    <?php Modal::begin([ 'id'=>'myModal', 'header' => '<h2>标题</h2>']); echo '内容'; M ...

  4. [leetcode]_Pascal's Triangle II

    题目:Pascal三角的变形,要求只用O(K)的额外空间. 思路:由于Pascal三角中,tri[n][i] = tri[n - 1][i] + tri[n-1][i-1],(通常情况下) 如果已经获 ...

  5. [译]Memory Reordering Caught in the Act

    原文:http://preshing.com/20120515/memory-reordering-caught-in-the-act/ 编写lock-free的C/C++程序时,在保证memory  ...

  6. 【php学习之路】php基础语法

    一.什么是php?       PHP即PHP: Hypertext Preprocessor(超文本处理器),是一种服务器端脚本语言,适用于创建web站点.开源免费 二.php能做什么?       ...

  7. DOS下无法调出中文输入法-Solved

    From:http://www.cnblogs.com/killerlegend/p/3750542.html Author:KillerLegend Date:2014.5.24 DOS下无法打开中 ...

  8. ASP.NET中前台调用后台的方法

    学习文章:http://www.cnblogs.com/kingteach/archive/2010/11/12/1875633.html 练习代码: 前台: <html xmlns=" ...

  9. Scrapy Learning笔记(四)- Scrapy双向爬取

    摘要:介绍了使用Scrapy进行双向爬取(对付分类信息网站)的方法. 所谓的双向爬取是指以下这种情况,我要对某个生活分类信息的网站进行数据爬取,譬如要爬取租房信息栏目,我在该栏目的索引页看到如下页面, ...

  10. 第一章 管理程序流(In .net4.5) 之 实现多线程和异步处理

    1. 概述 本章主要讲解.net4.5如何实现多线程和异步处理的相关内容. 2. 主要内容 2.1 理解线程 ① 使用Thread类   public static class Program   { ...