LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
2012-09-21 04:47
501 查看
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.
代码分析:
O(n)的解法。用Stack 存放左括号的index,碰到右括号,Pop出一个左括号的index,根据情况计算最长合理括号长度(如果stack.count == 0,从start开始算,如果stack还有东西,从最近一个左括号开始算)。
例如 "())(())("
"()((()()"
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 static int LogestValidParentheses(string s) { if (s.Length <= 1) return 0; Stack<int> stack = new Stack<int>(); int start = s.Length; int curr_length = 0; int max_length = 0; for(int i = 0; i < s.Length; i++) { if (s[i] == '(') stack.Push(i); if (s[i] == ')') { //if invalid parentheses in the middle set start back to s.Length if (stack.Count == 0) { start = s.Length; } else { start = Math.Min(start, stack.Pop()); if (stack.Count == 0) { curr_length = i - start + 1; max_length = Math.Max(curr_length, max_length); } else { //if some left parentheses indices in the stack curr_length = i - stack.Peek(); max_length = Math.Max(curr_length, max_length); } } } } return max_length; }
代码分析:
O(n)的解法。用Stack 存放左括号的index,碰到右括号,Pop出一个左括号的index,根据情况计算最长合理括号长度(如果stack.count == 0,从start开始算,如果stack还有东西,从最近一个左括号开始算)。
例如 "())(())("
( | ) | ) | ( | ( | ) | ) | ( | |
Stack | [0) | [) | [) | [3) | [3,4) | [3) | [) | [) |
start | 8 | 0 | 8 | 8 | 8 | 4 | 3 | 3 |
curr_legnth | 0 | 2 | 0 | 0 | 0 | 2 | 4 | 4 |
max_length | 0 | 2 | 2 | 2 | 2 | 2 | 4 | 4 |
( | ) | ( | ( | ( | ) | ( | ) | |
Stack | [0) | [) | [2) | [2,3) | [2,3,4) | [2,3) | [2,3,6) | [2,3) |
start | 7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
curr_length | 0 | 2 | 2 | 2 | 2 | 2 | 2 | 4 |
max_length | 0 | 2 | 2 | 2 | 2 | 2 | 2 | 4 |
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Valid Parentheses
- 【leetcode】第32题 Longest Valid Parentheses 题目+解析+代码
- LeetCode题目:32. Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Longest Common Prefix
- LeetCode算法题目:Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Longest Palindromic Substring
- leetcode做题总结,题目Longest Valid Parentheses 2012/02/29
- LeetCode力扣之Longest Valid Parentheses
- LeetCode_Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Generate Parentheses
- Leetcode || Longest Valid Parentheses
- leetcode problem 32 -- Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- [LeetCode] Longest Valid Parentheses
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode刷题笔录Longest Valid Parentheses
- LeetCode 032 Longest Valid Parentheses