您的位置:首页 > 编程语言 > C#

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.

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)[)[)
start80888433
curr_legnth02000244
max_length02222244
    "()((()()"

()((()()
Stack[0)[)[2)[2,3)[2,3,4)[2,3)[2,3,6)[2,3)
start70000000
curr_length02222224
max_length02222224
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: