【Longest Valid Parentheses】cpp
题目:
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的更多相关文章
- 【Valid Parentheses】cpp
题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...
- 【Longest Common Prefix】cpp
题目: Write a function to find the longest common prefix string amongst an array of strings. 代码: class ...
- 【Longest Palindromic Substring】cpp
题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...
- 【Longest Consecutive Sequence】cpp
题目: Given an unsorted array of integers, find the length of the longest consecutive elements sequenc ...
- 【leetcode】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- 【leetcode】 Longest Valid Parentheses (hard)★
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【LeetCode练习题】Longest Valid Parentheses
Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...
- 【Python】32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【一天一道LeetCode】#32. Longest Valid Parentheses
一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...
随机推荐
- Android开发教程大全介绍
Android是由谷歌在2007年推出的一个开放系统平台,主要针对移动设备市场,目前版本为Android 4.0.Android基于Linux,开发者可以使用Java或C/C++开发Android应用 ...
- JQuery 的几个有用的技巧
JQuery代码 /* 新窗口打开链接:JQuery filter attr * 禁止鼠标弹出右键菜单:DOM contextmenu * 回到页面顶端:DOM scrollTo * 动态更换Css样 ...
- WebApi调试中遇到的一些问题
今天对WebApi的项目进行了一些调试,得到了一些教训,记录下来,也让大家少花些时间在这些无用功上面. (1)Fiddler 进行Post参数提交 刚开始,都是使用的Fiddler对服务进行调试,一直 ...
- sqlserver 保留小数方法
1. 使用 Round() 函数,如 Round(@num,2) 参数 2 表示 保留两位有效数字. 2. 更好的方法是使用 Convert(decimal(18,2),@num) 实现转换,dec ...
- c#中操作word文档-三、MSDN文档
这是关于word读写的MSDN内容,基本所有的方法都可以在这上面找到 https://msdn.microsoft.com/zh-cn/library/office/ff837519.aspx
- MongoDB(1):常用操作命令大全
MongoDB常用操作命令大全(转) http://www.jb51.net/article/48217.htm 成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操 ...
- ASP.NET MVC5学习笔记之Filter基本介绍
Filter是ASP.NET MVC框架提供的基于AOP(面向方面)设计,提供在Action执行前后做一些非业务逻辑通用处理,如用户验证,缓存等.现在来看看Filter相关的一些类型信息. 一.基本类 ...
- C#高级功能(一)Lambda 表达式
Lambda 表达式是一种可用于创建委托或表达式目录树类型的匿名函数. 通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数. Lambda 表达式对于编写 LINQ ...
- C++不完整的类型
今天写C++primer 5th中文版第422页的程序时,出现了”不允许使用不完整的类型“的错误,下面我就用类A 与 类B 作为代表,重现一下该错误,并且提出解决方案. 一.带问题的类设计A: 1.类 ...
- python杂记-3(购买商品)
#!/usr/bin/env python# -*- coding: utf-8 -*-#如下是一个购物程序:#先输入工资,显示商品列表,购买,quit退出,最后格式化输出所买的商品.count = ...