Longest Valid Parentheses

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.

括号匹配的常规思路就是用进出栈。

但是这题的关键在于“连续匹配”,因此计算“连续匹配”长度时,本质就是求不匹配的括号之间最大长度。

也就是求进栈但未出栈的括号下标之间的最大差值。

注意边界:

(1)第一个留在栈中的括号之前的连续匹配长度。

(2)最后一个留在栈中的括号之后的连续匹配长度。

解法一:栈中记录未匹配括号的下标。在全部扫描s之后,将未匹配的括号逐个出栈进行计算。

class Solution {
public:
int longestValidParentheses(string s) {
int ret = ;
stack<int> stk; //store the indexes of unmatched parentheses
for(int i = ; i < s.size(); i ++)
{
if(s[i] == '(')
//unmatch
stk.push(i);
else
{//s[i] == ')'
if(!stk.empty() && s[stk.top()] == '(')
//match
stk.pop();
else
//unmatch
stk.push(i);
}
}
if(stk.empty())
//all match
ret = s.size();
else
{//check every unmatched pair of parentheses
int start;
int end = s.size()-;
while(!stk.empty())
{
start = stk.top();
stk.pop();
ret = max(ret, end-start);
end = start-;
}
//from begin to the first unmatched parenthese
ret = max(ret, end+);
}
return ret;
}
};

解法二:栈中记录括号及下标。在每次进站时计算与上个未匹配括号的距离。

struct Par
{
char c;
int ind;
Par(char newc, int newind): c(newc), ind(newind) {}
}; class Solution {
public:
int longestValidParentheses(string s) {
if(s == "")
return ; stack<Par> stk;
int ret = ;
int ind;
for(int i = ; i < s.size(); i ++)
{
if(s[i] == '(')
{
if(!stk.empty())
// distance between new unmatched parenthese and last unmatched parenthese
ret = max(ret, i-stk.top().ind-);
else
// distance between string begin and first unmatched parenthese
ret = max(ret, i);
Par p(s[i], i);
stk.push(p);
}
else if(s[i] == ')')
{
if(!stk.empty())
{
if(stk.top().c == '(')
stk.pop();
else
{// distance between new unmatched parenthese and last unmatched parenthese
ret = max(ret, i-stk.top().ind-);
Par p(s[i], i);
stk.push(p);
}
}
else
{// distance between string begin and first unmatched parenthese
ret = max(ret, i);
Par p(s[i], i);
stk.push(p);
}
}
}
if(stk.empty())
{//all matched
return s.size();
}
// distance between string end and last unmatched parenthese
ret = max(ret, (int)s.size()-stk.top().ind-); return ret;
}
};

【LeetCode】32. Longest Valid Parentheses (2 solutions)的更多相关文章

  1. 【LeetCode】32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  2. 【一天一道LeetCode】#32. Longest Valid Parentheses

    一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...

  3. 【Python】32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. [Leetcode][Python]32: Longest Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...

  5. leetcode problem 32 -- Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  6. 【LeetCode】14. Longest Common Prefix (2 solutions)

    Longest Common Prefix Write a function to find the longest common prefix string amongst an array of ...

  7. leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、

    20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...

  8. 刷题32. Longest Valid Parentheses

    一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过 ...

  9. 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)

    [LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...

随机推荐

  1. [MAC OS] NSButton tag 获取

    @IBAction func switchContentLayout(_ sender: Any) { let button : NSButton = sender as! NSButton;}

  2. HBase性能优化方法总结(转)

    原文链接:HBase性能优化方法总结(一):表的设计 本文主要是从HBase应用程序设计与开发的角度,总结几种常用的性能优化方法.有关HBase系统配置级别的优化,可参考:淘宝Ken Wu同学的博客. ...

  3. ubuntu下mongodb启动脚本

    run-mongodb.sh #!/bin/bash mongod --dbpath /usr/local/mongodb/data1 --logpath /usr/local/mongodb/log ...

  4. 在JSP中应用JavaBean

    1. 解决中文乱码的JavaBean 在JSP页面中,处理中文字符经常会出现字符乱码的现象,特别是通过表单传递中文数据时容易产生.它的解决办法有很多,如将request的字符集指定为中文字符集,编写J ...

  5. C#中属性PropertyInfo的使用

    昨天编程遇到一个问题两个类字段都是二十多个,其中有十多个是相同的,需要将一个类的字段赋值给另外一个类,开始的自己想手动的一个个去赋值,后来想来一下C#基础知识,用PropertyInfo就可以解决类似 ...

  6. 11个JavaScript颜色选择器插件

    几年前,很难找到一个合适的颜色选择器.正好看到很多不错的JavaScript颜色选择器插件,故而把这些编译汇总.在本文,Web设计师和开发人员 Kevin Liew 选取了11个相应插件,有些会比较复 ...

  7. TreeListControl:设置行样式

    <Style x:Key="OddEvenRowStyle" TargetType="{x:Type dxg:GridRowContent}"> & ...

  8. Unity3d---> IEnumerator

    Unity3d---> IEnumerator 2013-04-18 10:24 2162人阅读 评论(0) 收藏 举报 Unity3dc# using UnityEngine; using S ...

  9. XGBoost:在Python中使用XGBoost

    原文:http://blog.csdn.net/zc02051126/article/details/46771793 在Python中使用XGBoost 下面将介绍XGBoost的Python模块, ...

  10. 避免闪烁的方法(OnEraseBkgnd)

    在图形图象处理编程过程中,双缓冲是一种主要的技术.我们知道,假设窗口在响应WM_PAINT消息的时候要进行复杂的图形处理,那么窗口在重绘时因为过频的刷新而引起闪烁现象. 解决这一问题的有效方法就是双缓 ...