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. 常用的OpenCV函数速查

    常用的OpenCV函数速查 1.cvLoadImage:将图像文件加载至内存: 2.cvNamedWindow:在屏幕上创建一个窗口: 3.cvShowImage:在一个已创建好的窗口中显示图像: 4 ...

  2. Objective-C:MRC(引用计数器)在OC内部的可变对象是适用的,不可变对象是不适用的(例如 NSString、NSArray等)

    引用计数和字符串 内存中的常量字符串的空间分配与其他对象不同,他们没有引用计数机制 凡是自定义的对象都有引用计数机制: OC内部中对象分为可变对象(NSMutableString等)和不可变对象(NS ...

  3. go语言基础之init函数的介绍

    1.init函数的介绍 示例: 文件夹目录如下: 源代码: vi main.go   //程序入口 package main //必须 import ( "calc" " ...

  4. [模仿微软Live.cn]JavaScript输入邮箱自动提示

    原理是:在一个输入框 中,当我输入任何字的时候 自动下拉相应的邮箱提示,在输入框输入123的时候 下拉框有所有123的邮箱 输入其他的时候 有其他文案对应的邮箱. 同理 此插件不需要任何html标签, ...

  5. relatedTarget、fromElement、toElement相关元素

    在发生mouseover和mouseout事件时,还会涉及更多的元素.这两个事件都会涉及把鼠标指针从一个元素的边界之内移到另一个元素边界之内.对mouseover事件而言,事件的主目标是获得光标的元素 ...

  6. 怎样在Ubuntu中修改默认程序

    这个新手指南会向你展示如何在 Ubuntu Linux 中修改默认程序.对于我来说,安装 VLC 多媒体播放器是安装完 Ubuntu 16.04 该做的事中最先做的几件事之一.为了能够使我双击一个视频 ...

  7. Python标准库:内置函数abs(x)

    返回数字的绝对值. 參数能够是整数或浮点数.假设參数是复数,则返回复数的模. 因此abs()函数的注意点就是复数的不一样计算方式. 样例: #正整数 print('abs(1):', abs(1)) ...

  8. linux环境中设置jacoco覆盖率

    cd /alidata1/admin/za-themis pkill -9 -f za-themis #CATALINA_HOME=/root/za-tomcat #CATALINA_BASE=/ro ...

  9. HTTP请求格式和HTTP响应格式

    主要内容: 1.HTTP请求格式 2.HTTP响应格式 一.HTTP请求格式 当浏览器向Web服务器发出请求时,它向服务器传递了一个数据块,也就是请求信息,HTTP请求信息由3部分组成:l   请求方 ...

  10. C语言打印字母金字塔(第一行是A 第二行是ABA ……)

    #include <stdio.h> #include <stdlib.h> int main() { int line;//代表行数 int i; char letter,c ...