Leetcode 32: Longest Valid Parentheses
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于Leetcode 32: Longest Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 32. Longest Valid Parentheses
LeetCode 32. Longest Valid Parentheses
LeetCode 32. Longest Valid Parentheses
[leetcode-32-Longest Valid Parentheses]