码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 32: Longest Valid Parentheses

时间:2017-11-04 13:34:15      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:bst   nbsp   bsp   contain   rip   style   class   result   and   

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

标签:bst   nbsp   bsp   contain   rip   style   class   result   and   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!