【LeetCode】Longest Valid Parentheses
来源:互联网 发布:岁月神偷 网络歌手 编辑:程序博客网 时间:2024/06/13 04:01
题目描述:
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.
对每个i进行扫描找到以i为起点的最长合法字符串然后比较当然是可行的,但是O(n^2)复杂度。
这题目一看就有O(n)的解法。一开始想的很复杂,思路是扫描整个字符串,对每个字符做if else处理,用count记录下之前'('的数目,每遇到一个')'长度++。但是这样没法有效分割合法字符串,例如遇到"(()(((()(((()(()"的时候会需要不定数目的变量来记录前个合法字符串的长度,不太好解。
后来想到的解法是这样的,用vector<bool> 来记录某位置字符是否是合法字符串的成员。用一个栈,每遇到一个'('就将index进栈,遇到')'时该位置记录为true,同时出栈并将出栈位置标记为true。最后生成的就是一个01组成的显而易见的数组了。
代码如下:
class Solution {public:int longestValidParentheses(string s) {stack<int> left;vector<bool> dist(s.length(), false);int res(0);for (int i = 0; i < s.length(); i++){if (s[i] == '(')left.push(i);else if (!left.empty()){dist[i] = true;dist[left.top()] = true;left.pop();}}int count(0);for (int i = 0; i < dist.size(); i++){if (dist[i]){count++;res = max(res, count);}elsecount = 0;}return res;}};
0 0
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses
- LeetCode-Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- LeetCode:Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses
- Leetcode:Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- 操作系统 内存管理-虚拟内存
- Longest Common Prefix
- jQuery setTimeout传递字符串参数报错怎么办?解决方法
- 将ibatis的sql打印在控制台
- 【leetcode】Climbing Stairs
- 【LeetCode】Longest Valid Parentheses
- 在Eclipse的kepler中运行OSGI工程出错的解决方案
- An Introduction To Tkinter
- POJ 3370 Halloween treats 鸽巢原理 解题
- 回文数的判断
- Unity3D调用第三方SDK(之一)从eclipse到Unity3D.
- Android xml配置动画效果
- HPUX---hpux的核心参数
- 数据挖掘技术、方法及应用