LeetCode--032--最长有效括号(java)

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"

示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

start纪录第一个有效括号的位置,当遇到右括号时,看和其匹配的左括号的位置在哪,得到该有效括号的长度。

 1 class Solution {
 2     public int longestValidParentheses(String s) {
 3         Stack<Integer> stack = new Stack();
 4         int start = -1;//当情况为(()) 3 + 1 = 4
 5         int res = 0;
 6         for(int i = 0;i < s.length();i++){
 7             if(s.charAt(i) == '('){
 8                 stack.push(i);
 9             }else{
10                 if(stack.isEmpty()){
11                     start = i;
12                 }else{
13                     stack.pop();
14                     if(stack.isEmpty()){
15                         res = Math.max(res,i-start);
16                     }else{
17                         res = Math.max(res,i - stack.peek());
18                     }
19                 }
20             }
21         }
22         return res;
23     }
24 }

2019-04-25 18:39:32

posted @ 2019-04-25 18:48  Assange  阅读(373)  评论(0编辑  收藏  举报