首页 > 其他 > 详细

Leetcode 32: Longest Valid Parentheses

时间:2017-11-04 12:31:58      阅读:212      评论:0      收藏:0      [点我收藏+]

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 class Solution {
 2     public int LongestValidParentheses(string s) {
 3         int result = 0, cur = 0;
 4         var stack = new Stack<Tuple<char, int>>();
 5         bool lastPop = false;
 6         stack.Push(new Tuple<char, int>(*, -1));
 7         
 8         for (int j = 0; j < s.Length; j++)
 9         {
10             if (s[j] == ()
11             {
12                 stack.Push(new Tuple<char, int>(s[j], j));
13             }
14             else
15             {
16                 if (stack.Count > 0 && stack.Peek().Item1 == ()
17                 {
18                     stack.Pop();
19                     result = Math.Max(result, j - stack.Peek().Item2);
20                 }
21                 else
22                 {
23                     stack.Push(new Tuple<char, int>(s[j], j));
24                 }
25             }
26         }
27         
28         return result;
29     }
30 }

 

Leetcode 32: Longest Valid Parentheses

原文:http://www.cnblogs.com/liangmou/p/7782939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!