108-Longest Valid Parentheses
来源:互联网 发布:淘宝视频用什么拍好看 编辑:程序博客网 时间:2024/05/16 05:34
-32. Longest Valid Parentheses My Submissions QuestionEditorial Solution
Total Accepted: 64569 Total Submissions: 285723 Difficulty: Hard
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.
Subscribe to see which companies asked this question
class Solution {public: int longestValidParentheses(string s) { int max_len=0,last = -1; int n= s.size(); stack<int> lefts; for(int i=0;i<n;++i){ if(s[i]=='(')lefts.push(i);//如果是左括号,一直入栈 else{ if(lefts.empty()){//一直遇到右括号“)))))”,如果栈空,记录last的位置, //总是在第一个合法位置的前一个位置 last = i; } else{//遇到右括号且栈不为空,那么出栈且计算当前最大值 lefts.pop(); if(lefts.empty())//空了,记录上一次合法的第一个位置,序列")))))()",出栈之前“(” max_len = max(max_len,i-last); else max_len = max(max_len,i-lefts.top());//这种情况,序列“((()”,出栈前“(((” } } } return max_len; } /**********************动态规划******************************* *记f[i]为以i开头的合法括号长度最大值 *1.这种情况“(()()())”f[i]=f[i+1]+2, *如果s[i]与s[i+f[i+1]+1]匹配,match=i+f[i+1]+1 *即一个是'(',一个是')' *2.如果是这样“(()()())()”,f[i]=f[i]+f[match+1] ***********************************************************/ int longestValidParentheses_2(string s) { int n = s.size(); vector<int> f(n,0); int res=0; for(int i=n-2;i>=0;--i){ int match = i+f[i+1]+1; if(s[i]=='('&& match<n &&s[match]==')'){ f[i]=f[i+1]+2; if(match+1<n)f[i]+=f[match+1]; } res = max(res,f[i]); } return res; }};
0 0
- 108-Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Longest Valid Parentheses
- Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode31:Longest Valid Parentheses
- longest valid parentheses
- Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- Longest Valid Parentheses
- Longest Valid Parentheses
- Jquery自带的弹出框效果
- 数据结构:数组+链表(巧妙!)
- mysql5.5 主从复制配置过程
- Nginx Location配置总结
- Android初级教程三个Dialog对话框小案例
- 108-Longest Valid Parentheses
- 测试机器是否为 大端or小端
- Android蓝牙BLE(一)--使用介绍
- Firefox浏览器关于submit提交表单时提交两次的bug
- 《深入理解Java虚拟机(第2版)》的笔记-第89页
- leetcode_c++:Longest Consecutive Sequence(128)
- JAVA特性多态之覆盖
- 数据库4 3层结构(Three Level Architecture) DBA DML DDL DCL DQL
- JS匀速运动