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

Longest Valid Parentheses

时间:2014-10-09 17:06:08      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   java   for   sp   div   on   

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.

答案

public class Solution {
    public int longestValidParentheses(String s) {
        if(s==null||s.length()<=1)
        {
            return 0;
        }
        char []array=s.toCharArray();
        int i=0;
        int j=0;
        int result=0;
        for(j=1;j<array.length;j++)
        {
            if(array[j]==')')
            {
                if(i>=0&&array[i]=='(')
                {
                    array[i]=0;
                    array[j]=0;
                    while(i>=0&&array[i]==0)
                    {
                        i--;
                    }
                    result=Math.max(result,j-i);
                    continue;
                }
            }
            i=j;
        }
        return result;
    }
}


Longest Valid Parentheses

标签:style   color   io   ar   java   for   sp   div   on   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39925527

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