LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses

本文介绍了一种O(n)复杂度的算法,用于在给定字符串中找到最长的有效括号子串,并详细解释了算法实现过程及示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 1         public static int LogestValidParentheses(string s)
 2         {
 3             if (s.Length <= 1)
 4                 return 0;
 5 
 6             Stack<int> stack = new Stack<int>();
 7 
 8             int start = s.Length;
 9             int curr_length = 0;
10             int max_length = 0;
11 
12             for(int i = 0; i < s.Length; i++)
13             {
14                 if (s[i] == '(')
15                     stack.Push(i);
16 
17                 if (s[i] == ')')
18                 {
19                     //if invalid parentheses in the middle set start back to s.Length
20                     if (stack.Count == 0)
21                     {
22                         start = s.Length;
23                     }
24                     else
25                     {
26                         start = Math.Min(start, stack.Pop());
27                         if (stack.Count == 0)
28                         {
29                             curr_length = i - start + 1;
30                             max_length = Math.Max(curr_length, max_length);
31                         }
32                         else
33                         {
34                             //if some left parentheses indices in the stack
35                             curr_length = i - stack.Peek();
36                             max_length = Math.Max(curr_length, max_length);
37                         }
38                     }
39                 }
40             }
41 
42             return max_length;
43         }

代码分析:

  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

 

 

转载于:https://www.cnblogs.com/etcow/archive/2012/09/21/2696264.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值