4.1.2 Longest Valid Parentheses
来源:互联网 发布:中铁一局集团网络学校 编辑:程序博客网 时间:2024/06/10 13:59
原题链接: https://oj.leetcode.com/problems/longest-valid-parentheses/
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.
public class Solution { public int longestValidParentheses(String s) { Stack<Character> stack = new Stack<Character>(); int length = 0; int maxLength = 0; char c; for(int i = 0; i < s.length(); i++){ c = s.charAt(i); if(c == '(' ){ stack.push(c); } if(c == ')'){ if(stack.isEmpty()){ continue; } char d = stack.peek(); if(d == '(' && c!= ')') { length = 0; continue; } else { stack.pop(); length = length + 2; if(length > maxLength){ maxLength = length; } } } } return maxLength; }}
但是这个是不对的。Input:"()(()"Output:4Expected:2Input:"()(())"Output:4Expected:6
为什么?
正确的代码:
方法I: 栈。Time O(n), Space O(n)
思路: “所有无法匹配的')'”的index其实都是各个group的分界点”
(引用:http://www.cnblogs.com/lichen782/p/leetcode_Longest_Valid_Parentheses.html)
public class Solution { public int longestValidParentheses(String s) { //code after reading dai's c++ code //each ) is used to separate groups of valid parentheses Stack<Integer> lefts = new Stack<Integer>();//store the indices of '(' int length = 0; int maxLen = 0; int last = -1; char c; for(int i = 0; i < s.length(); i++){ c = s.charAt(i); if(c == '('){ lefts.push(i); } else{//c == ')' if(lefts.isEmpty()){//this ) should be used as the separation point last = i; } else{ lefts.pop();//match the current ) with previous () if(lefts.isEmpty()){//this group has completed maxLen = Math.max(maxLen, i - last); } else{ maxLen = Math.max(maxLen, i - lefts.peek()); } } } } return maxLen; }}
方法II: DP 不懂。todo
方法III: 两边扫描。不懂为什么work. todo.
0 0
- 4.1.2 Longest Valid Parentheses
- 4.1.2 Longest Valid Parentheses
- 4.1.2—栈—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
- 东软实训(十一)
- 基于流形距离的聚类算法
- Single Number II
- xml解析错误:UTFDataFormatException: invalid byte 2 of 2-byte UTF-8 sequence (0xfd)
- POJ 2075 Tangled in Cables (c++/java)
- 4.1.2 Longest Valid Parentheses
- Disruptor 3种EventProcessor实现类
- 地火明夷
- 如何选项目?
- Android studio for mac 安装
- Python 对Twitter中指定话题的被转载Tweet数量的频谱分析
- 3Sum
- Spring容器初始化
- Direct3D 纹理使用