`
hcx2013
  • 浏览: 88787 次
社区版块
存档分类
最新评论

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.

 

public class Solution {
    public int longestValidParentheses(String s) {
        if (s == null || s.length() == 0) {
        	return 0;
        }
        Stack<Integer> stack = new Stack<Integer>();
        int start = 0;
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				stack.push(i);
			} else {
				if (stack.isEmpty()) {
					start = i + 1;
				} else {
					stack.pop();
					if (stack.isEmpty()) {
						res = Math.max(res, i-start+1); 
					} else {
						res = Math.max(res, i-stack.peek());
					}
				}
			}
		}
        return res;
    }
}

 

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics