博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
阅读量:4318 次
发布时间:2019-06-06

本文共 2332 字,大约阅读时间需要 7 分钟。

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
stack = new Stack
(); 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.Length20 if (stack.Count == 0)21 {22 start = s.Length;23 }24 else25 {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 else33 {34 //if some left parentheses indices in the stack35 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) [) [)
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

 

 

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

你可能感兴趣的文章
swift--调用系统单例实现打电话
查看>>
0038-算一算是一年中的第几天
查看>>
51nod 1094 【水题】
查看>>
003.第一个动画:绘制直线
查看>>
ng-深度学习-课程笔记-2: 神经网络中的逻辑回归(Week2)
查看>>
正则表达式的搜索和替换
查看>>
个人项目:WC
查看>>
地鼠的困境SSL1333 最大匹配
查看>>
flume+elasticsearch+kibana遇到的坑
查看>>
【MM系列】在SAP里查看数据的方法
查看>>
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>