第32题 最长匹配括号

题目:

找出字符串中最长匹配括号的长度,如“)()())()()(”,结果为4

思路:

)  (  ) (  )  ) (  ) (  )  (

0 1 2 3 4 5 6 7 8 9 10

用一个栈去存储索引,当当前字符为“)”或栈为空时,存储该字符,当栈顶的索引对应的字符为“(”,并且当前字符为“)”时,弹出栈顶字符,并用当前字符索引减去当前栈顶的值,即当前找到的最大长度。

代码:

package T032;

import java.util.Stack;

public class LongestValidParentheses {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(longestValidParentheses(")()())()()("));
    }
    public static int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<>();
        int result = 0;
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '(') {
                stack.pop();
                result = Math.max(result, i - stack.peek());
            } else {
                stack.push(i);
            }
        }
        return result;
    }
}

 

原文地址:https://www.cnblogs.com/wuchaodzxx/p/5896304.html