31. Longest Valid Parentheses
2013-09-22 12:20
148 查看
Given a string containing just the characters
For
Another example is
---
'('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) { int maxLen = 0, last = -1; Stack<Integer> lefts = new Stack<Integer>(); for (int i=0; i<s.length(); ++i) { if (s.charAt(i)=='(') { lefts.push(i); } else { if (lefts.isEmpty()) { // no matching left last = i; } else { // find a matching pair lefts.pop(); if (lefts.isEmpty()) { maxLen = Math.max(maxLen, i-last); } else { maxLen = Math.max(maxLen, i-lefts.peek()); } } } } return maxLen; } }
相关文章推荐
- LeetCode 31. Longest Valid Parentheses O(n)实现
- 20. Valid Parentheses
- 20. Valid Parentheses
- 32. Longest Valid Parentheses
- [C语言][LeetCode][20]Valid Parentheses
- 20. Valid Parentheses \ 71. Simplify Path
- LeetCode-20. Valid Parentheses
- 32. Longest Valid Parentheses
- 56:Longest Valid Parentheses
- [勇者闯LeetCode] 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- Leetcode Algorithm 032. Longest Valid Parentheses
- validParentheses
- [LeetCode] Longest Valid Parentheses
- 32. Longest Valid Parentheses
- [leetcode]Longest Valid Parentheses
- Leetcode题解 - 20. Valid Parentheses
- Valid Parentheses
- LeetCode 20 Valid Parentheses
- Valid Parentheses