Longest Valid Parentheses
来源:互联网 发布:淘宝开店链接 编辑:程序博客网 时间:2024/05/01 10:02
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.
解题思路:利用stack在扫描字符串的过程中判断合法的子字符串的区间并保存起来,接下来要做的便是利用O(n)的时间复杂度合并区间,由于stack的关系,大区间的索引肯定在小区间的后面,这样我们从后往前标记区间便可以实现O(n)的时间复杂度,最终求解最长的区间即可,算法总的时间复杂度是O(n)的。
class Solution {public: int longestValidParentheses(string s) { int ans = 0, cnt = 0; int sp, ep; int size = s.length(); stack<int> stk; vector< pair<int,int> > vec; bool mark[100010]; memset(mark, false, sizeof(mark)); for(int i = 0; i < size; ++i) { if(s[i] == ')') { if(stk.empty()) { continue; } else { vec.push_back(make_pair(stk.top(), i)); stk.pop(); } } else { stk.push(i); } } size = vec.size(); for(int i = size - 1; i >= 0; --i) { sp = vec[i].first, ep = vec[i].second; if(mark[vec[i].first]) continue; for(int j = sp; j <= ep; ++j) { mark[j] = true; } } size = s.length(); for(int i = 0; i < size; ++i) { if(!mark[i]) { ans = max(ans, cnt); cnt = 0; } else { cnt++; } } ans = max(ans, cnt); return ans; }};
0 0
- 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
- Longest Valid Parentheses
- Gephi 0.8.2-beta for Mac安装问题汇总
- 认识自己——我几年的生活
- iOS中cookie的保存与恢复
- linux的udev和sysfs
- rsync+ssh同步备份文件
- Longest Valid Parentheses
- poj_1860
- 论ERP系统开发 二:框架结构
- 机器学习实战——条件随机场(CRF)
- 搞定linux上MySQL编程(六):C语言编写MySQL程序(结)
- oralce用存储过程实现分页 以及 用java调用这个存储过程的代码
- 双向链表(1) - 基本介绍以及插入节点
- hznu 1139: Minimax Triangulation(dp,三角形面积模板)
- 中文版android开发资源