一、题目说明

题目是32. Longest Valid Parentheses,求最大匹配的括号长度。题目的难度是Hard

二、我的做题方法

简单理解了一下,用栈就可以实现。实际上是我考虑简单了,经过5次提交终于正确了。

性能如下:

Runtime: 8 ms, faster than 61.76% of C++ online submissions for Longest Valid Parentheses.
Memory Usage: 9.8 MB, less than 10.71% of C++ online submissions for Longest Valid Parentheses.

代码如下:

#include<iostream>
#include<vector>
#include<stack>
using namespace std; class Solution {
public:
int longestValidParentheses(string s){
if(s.size()<=1) return 0; stack<char> st;
vector<int> result; for(int t=0;t<s.size();t++){
if(s[t]=='('){
st.push(s[t]);
result.push_back(0);
}else if(s[t]==')'){
if(st.empty()){
result.push_back(0);
}else if(st.top() == '('){
st.pop();
if(result.back()>0){
int s = result.size()-1;
//合并所有非 0
while(s>0 && result[s]>0){
s--;
}
if(s < result.size()-2){
int sum = 0,currSize = result.size();
for(int j=s+1;j<currSize-1;j++){
sum += result.back();
result.pop_back();
}
result.back() += sum;
} int tmp = result.back() + 2;
if(result.size()>0){
result.pop_back();
}
result.back() += tmp; }else{
result.back() += 2;
} }
}
} int max=0,curMax=0;
for(int i=0;i<result.size();i++){
curMax = 0;
int t = i;
while(t<result.size() && result[t]>0){
curMax += result[t];
t++;
}
max = curMax>max ? curMax : max;
} return max;
}
};
int main(){
Solution s;
cout<<(2==s.longestValidParentheses("(()"))<<endl;
cout<<(4==s.longestValidParentheses(")()())"))<<endl;
cout<<(2==s.longestValidParentheses("()(()"))<<endl;
cout<<(6==s.longestValidParentheses("()(())"))<<endl;
cout<<(4==s.longestValidParentheses("(()()"))<<endl;
cout<<(4==s.longestValidParentheses("(())"))<<endl;
cout<<(6==s.longestValidParentheses("(()())"))<<endl;
cout<<(10==s.longestValidParentheses(")(())(()()))("))<<endl;
cout<<(8==s.longestValidParentheses("((()))())"))<<endl;
return 0;
}

三、优化措施

题解给了4种方法,这4种方法都比较好理解,我上述实现方法属于第3种“栈”,只不过把问题搞复杂了。惭愧!!!

1.暴力法,枚举所有子串,判断合法性,求出最长。

2.动态规划,这一直是我的软肋。

用数组dp表示,其中第 i 个元素表示以下标为 i 的字符结尾的最长有效子字符串的长度。

3.栈

4.不需要额外空间:这种方法非常巧妙,非常考验智商!理解起来不难!

用left和right分别统计左括号和右括号数量,先从左到右统计,遇到左括号left++,遇到右括号right++,如果right==left求最大值,如果left<right则将left=right=0;再从右到左来一遍。

刷题32. Longest Valid Parentheses的更多相关文章

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

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

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

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

  3. 32. Longest Valid Parentheses

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

  4. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

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

  5. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  6. 【LeetCode】32. Longest Valid Parentheses (2 solutions)

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

  7. leetcode 32. Longest Valid Parentheses

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

  8. Java [leetcode 32]Longest Valid Parentheses

    题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...

  9. leetcode problem 32 -- Longest Valid Parentheses

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

随机推荐

  1. 官方关于Dialog的介绍

    将Activity显示成Dialog的形式: Tip: If you want a custom dialog, you can instead display an Activity as a di ...

  2. C中的文件操作函数[笔记]

    头件 : #include<stdio.h> 两个必须函数: FILE * fopen(const char * path,const char * mode); //path:文件路径 ...

  3. Day6 - A - HH的项链 HYSBZ - 1878

    ------------恢复内容开始------------ HH有一串由各种漂亮的贝壳组成的项链.HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一 段贝壳,思考它们所表达的含义.H ...

  4. 【SQL必知必会笔记(3)】SELECT语句的WHERE子句数据过滤操作

    上个笔记主要介绍了利用SELECT语句检索单个/多个/所有列,并利用DISTINCT关键字检索具有唯一性的值.利用LIMIT/OFFSET子句限制结果:以及利用ORDER BY子句排序检索出的数据,主 ...

  5. python手动实现深拷贝

    深拷贝是将对象全拷贝,包括嵌套对象 def deepcopy(cls): if isinstance(cls, dict): dct = {} for k, v in cls.items(): dct ...

  6. (最详细)JAVA如何连接虚拟机的HBASE和hadoop(JAVA如何远程访问虚拟机HBASE)

    第一步: 首先把虚拟机和你的主机(本地电脑)弄通这样本地机器才能访问虚拟机里面的内容 我用的虚拟机为 VMware Workstation linux 为 centeros 补充一点虚拟机设置 1  ...

  7. unity基础开发----Unity获取PC,Ios系统的mac地址等信息

    在软件开发中可以会用到mac地址作为,设备的唯一标示,我们也可以通过unity获取,经测试pc,ios都可以但是安卓没有获取到. 代码如下: using UnityEngine; using Syst ...

  8. ffmpeg “inttypes.h”: No such file or directory

    编译过程:错误一:无法打开包括文件:“inttypes.h”: No such file or directory解决方法:删除之,并在其之前添加如下代码: #if defined(WIN32) &a ...

  9. JS - 获取任意一天的0点和23:59:59时间

    转载自 https://www.cnblogs.com/sk-3/archive/2019/07/23/11232750.html 使用了setHours() 方法 setHours() 方法用于设置 ...

  10. 使用Kickstart+pxe自动化安装部署无人值守的linux服务器

    Kickstart+pxe Kickstart无人职守安装RHEL5过程分享(详细图解版) 启动应用有:httpd.dhcpd.named.xinetd 无人职守自动批量安装linux系统超详细 参考 ...