(java)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.


解题思路:

这道题跟之前的一道题比较像,所以我的做法就是用栈的方式,如果当前的是')'而栈顶是'(',就对栈顶进行pop操作。反之将当前的char放入栈中。

这道题比较麻烦的就是,要来计算最大子串。不能单纯的看最后栈的存储量来决定,而是要看栈中存储的char在字符串中的位置。所以我就进行了相应的修改。用一个栈来存储char,一个栈来储存对应的index。(其实也可以只用一个存储index的栈,或者弄一个map什么的)。在每次要将char存入到栈中时,判断当前Index减去栈顶index是否大于1,大于1证明有子串存在,进行最大子串更新。


public class Solution {
    public int longestValidParentheses(String s) {
        int result = 0;
		int len1 = 0;
		int len2 = 0;
        Stack sstack = new Stack();
        Stack istack = new Stack();
        for(int i = 0;i0)
        			result = Math.max(result, i-istack.peek()-1);
            	istack.push(i);
        	}
        }
        if(!istack.isEmpty())
        	result = Math.max(s.length()-istack.peek()-1,result);
        else
        	result = s.length();
        return result;
    }
}


你可能感兴趣的:(leetcode)