Leetcode 32: Longest Valid Parentheses

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 }

 

posted @ 2017-11-04 11:49  逸朵  阅读(119)  评论(0)    收藏  举报