首页 > 其他 > 详细

LeetCode Longest Valid Parentheses

时间:2015-01-01 21:09:37      阅读:353      评论: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 public class Solution {
 2     public int longestValidParentheses(String s) {
 3         if (s == null) {
 4             return  0;
 5         }
 6         int maxlen=0;
 7         Stack<Integer> stack = new Stack<Integer>();
 8         stack.add(-1);
 9         for (int i = 0; i < s.length(); i++) {
10             if (s.charAt(i) == ‘(‘) {
11                 stack.add(i);
12             } else {
13                 stack.pop();
14                 if (stack.isEmpty()) {
15                     stack.add(i);
16                 } else {
17                     maxlen=Math.max(maxlen,i-stack.peek());
18                 } 
19             }
20         }
21         return maxlen;
22     }
23 }

 

LeetCode Longest Valid Parentheses

原文:http://www.cnblogs.com/birdhack/p/4197801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!