32. Longest Valid Parentheses
2016-09-18 10:17
288 查看
Given a string containing just the characters
For
Another example is
思路: 用栈来实现. 用栈存储左括号的下标, 对字符串进行从左到右的遍历,当遇到左括号时,将其下标压栈;当遇到右括号时,先判断栈是否为空,若是空,则将变量left更新为当前右括号下标,表示字符串匹配从left右边开始;若栈不为空,弹出一个,即左括号,若弹出后,栈为空,比较当前最大值和当前下标与left的差值的最大值,并更新;若不为空,则比较当前下标和栈顶元素的差值.
时间复杂度: O(N)
空间复杂度: O(N)
'('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.
思路: 用栈来实现. 用栈存储左括号的下标, 对字符串进行从左到右的遍历,当遇到左括号时,将其下标压栈;当遇到右括号时,先判断栈是否为空,若是空,则将变量left更新为当前右括号下标,表示字符串匹配从left右边开始;若栈不为空,弹出一个,即左括号,若弹出后,栈为空,比较当前最大值和当前下标与left的差值的最大值,并更新;若不为空,则比较当前下标和栈顶元素的差值.
时间复杂度: O(N)
空间复杂度: O(N)
public int longestValidParentheses(String s) { int longest=0; Stack<Integer> stack=new Stack<Integer>(); int left=-1; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(') stack.push(i); else{ if(stack.isEmpty()) left=i; else{ stack.pop(); if(stack.isEmpty()) longest=longest>(i-left)?longest:(i-left); else longest=longest>(i-stack.peek())?longest:(i-stack.peek());//连续的括号想匹配的长度 } } } return longest; }
相关文章推荐
- 32. Longest Valid Parentheses
- 【LeetCode】32. Longest Valid Parentheses (2 solutions)
- [LeetCode]32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- [leetcode]32. Longest Valid Parentheses(Java)
- 32. Longest Valid Parentheses (Stack; DP)
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- LeetCode 32. Longest Valid Parentheses(最长合法圆括号子序列)
- Leetcode刷题记——32. Longest Valid Parentheses(最长有效括号)
- [LeetCode]32. Longest Valid Parentheses
- leetcode题解-32. Longest Valid Parentheses
- [LeetCode] 32. Longest Valid Parentheses 最长有效括号
- Leetcode: 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- [leetcode] 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- [leetcode] 32. Longest Valid Parentheses 解题报告
- 32. Longest Valid Parentheses
- 【C++】 LeetCode 32. Longest Valid Parentheses