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

LeetCode -- Longest Valid Parentheses

时间:2015-09-25 13:20:58      阅读:109      评论: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.遍历s[i] ,i∈[0,n)并使用stack存当前索引i
2.如果s[i] 为 ‘)‘ 且stack不为空 且s[stack.Peek()] 为‘(‘
:stack弹出
如果stack为空 , max = i + 1
否则,max = Max(max,i-stack.Peek())
  否则(即s[i]为‘(‘),直接将s[i]入栈




实现代码:

public class Solution {
    public int LongestValidParentheses(string s) {
        int max = 0;
        var stack = new Stack<int>();
        for (int i = 0; i < s.Length; i++) {
            if (s[i] == ‘)‘ && stack.Count > 0 && s[stack.Peek()] == ‘(‘) {
                stack.Pop();
                if (stack.Count == 0){
    				max = i + 1;
    			}
                else{
    				max = Math.Max(max, i - stack.Peek());
    			}
            } else {
                stack.Push(i);
            }
        }
    	
        return max;
    }
}




	


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Longest Valid Parentheses

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/48731261

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