leetcode32
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(), longest = ;
stack<int> st;
for (int i = ; i < n; i++) {
if (s[i] == '(') st.push(i);
else {
if (!st.empty()) {
if (s[st.top()] == '(') st.pop();
else st.push(i);
}
else st.push(i);
}
}
if (st.empty()) longest = n;
else {
int a = n, b = ;
while (!st.empty()) {
b = st.top(); st.pop();
longest = max(longest, a-b-);
a = b;
}
longest = max(longest, a);
}
return longest;
}
};
参考:https://leetcode.com/problems/longest-valid-parentheses/discuss/14126/My-O(n)-solution-using-a-stack
补充一个python的实现:
class Solution:
def longestValidParentheses(self, s: str) -> int:
n = len(s)
longest = 0
st = []
for i in range(n):
if s[i] == '(':
st.append(i)
else:#s[i] == ')'
if len(st) > 0 and s[st[-1]] == '(':#前一位置是'('
st.pop(-1)#获得一个合法匹配
else:
st.append(i)
if len(st) == 0:#s所有字符都是合法括号对
longest = n
else:
a,b = n,0
while len(st) != 0:#st中记录的都是无法匹配的'('和')'出现的位置,可称为'单身括号'
b = st.pop(-1)
longest = max(longest,a-b-1)#计算当前'单身括号'与下一个'单身括号'的距离,就是最长合法substring(连续子串)的长度
a = b
longest = max(longest,a)
return longest
leetcode32的更多相关文章
- LeetCode32 Longest Valid Parentheses
题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...
- [Swift]LeetCode32. 最长有效括号 | Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Leetcode32. 最长有效括号
32. 最长有效括号 做法 \(f_{i}\)以\(i\)结尾的最长匹配 前提为\(s[i]=')'\) \(s[i-1]='('\),则\(f[i]=f[i-2]+2\) \(s[i-1]=')'\ ...
- leetcode32 最长游戏括号 dp
有一说一,我觉得这题没有到困难级 要保存之前的状态,感觉是很明显的dp 思路和题解一样 class Solution { public: int longestValidParentheses(str ...
随机推荐
- Jsの练习-数组常用方法
1. join() 方法: <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...
- MVC5 Api Area 区域
到Area区分不同的模块让项目结构更加的清晰 TODO 步骤如下: 项目 –> 添加 -> 区域 (Area) 添加路由规则 public static class WebApiConfi ...
- 一款非常不错的重写listctrl类-CListCtrlEx
原文在:https://www.codeproject.com/Articles/28063/An-Extended-MFC-CListCtrl-to-edit-individual-cells li ...
- L2-016. 愿天下有情人都是失散多年的兄妹(深搜)*
L2-016. 愿天下有情人都是失散多年的兄妹 参考博客 #include<iostream> #include<cstdio> #include<cstring> ...
- L2-013. 红色警报(并查集)*
L2-013. 红色警报 参考博客 #include <cstdio> #include <algorithm> #include <iostream> #incl ...
- linux 查看当前系统版本号
为避免现场未能完全安装系统,使用yum 安装版本需一致 第一种方法: [root@sky9896sky]# lsb_release -a bash:lsb_release: command not f ...
- 3.4 unittest之装饰器(@classmethod)
3.4 unittest之装饰器(@classmethod) 前言前面讲到unittest里面setUp可以在每次执行用例前执行,这样有效的减少了代码量,但是有个弊端,比如打开浏览器操作,每次执行用例 ...
- Python全栈之路----常用模块----datetime模块详解
相比于time模块,datetime模块的接口则更直观,更容易调用. datetime模块定义了下面这几个类: datetime.date:表示日期的类,常用的属性有year,month,day: d ...
- jmeter4.0安装记录
前提:jmeter需配置环境变量jdk,jmeter4.0版本需1.7以上版本, 查看jdk版本命令java -version 1.官网http://jmeter.apache.org/downloa ...
- linux下不能拼通www.baidu.com
1.打开虚拟机,通过命令修改内容如下 vi /etc/sysconfig/network-scripts/ifcfg-eth0 2.将信息修改如下: 3.ping www.baidu.com 查看是否 ...