leetCode练习(32)

题目:Longest Valid Parentheses

难度:hard

问题描述:

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.

解题思路:

首先我们会想到这道理的简单形式:判断一个字符串是否匹配,我们可以借鉴这一思路。

构造一个stack,一个boolean数组temp代表s的每个字符是否有与之相匹配的字符

每当遇到‘(‘,我们将其索引压入stack,当遇到’)‘,从stack中提出上一个‘(’的索引,将这两个索引的temp[i] [j]都设为ture。最后找到temp中最长的连续true即可。

具体代码如下:

public class h_32_LongestValidParentheses {
	public static int longestValidParentheses(String s) {
        if(s==null||s.length()<2)	return 0;
        Stack stack =new Stack<>();
        int len=s.length();
        boolean[] temp=new boolean[len];	//temp[i]=第i个字符是否有与之匹配的字符
        int i;
        int p=0;
        char c;
        //判断每个字符是否有与之匹配的字符
        while(pres){
        			res=p;
        		}
        		p=0;
        	}
        }
        if(p>res){
			res=p;
		}
        return res;
        
    }
	
	public static void main(String[]args){
		int  i=longestValidParentheses(")");
		System.out.println(i);
	}
}

你可能感兴趣的:(leetCode)