栈应用——最长括号匹配

问题描述:

    给定字符串,仅包含左括号'('和右括号')',它可能不是括号匹配的,设计算法,找出最长的括号字串,并返回字串的长度。

如:

    ((): 2

    ()(): 4

    ()(()):6

    (()()): 6

思路分析:

  • 记起始位置start = -1,最大匹配长度为max
  • 考虑当前位置i的符号:
    • 如果是'(',直接入栈;
    • 如果是')':
      • 如果栈空,则起始位置更新为i;
      • 如果栈不空,则肯定能与栈顶的左括号匹配,然后考虑弹出一个左括号后的栈:
        • 若栈空,则说明此次是一个匹配,匹配长度为:i-start,然后更新max;
        • 若栈不空,则当前栈顶元素t是上次匹配的最后位置,考虑匹配长度i-t,更新max;

 Code :

/**
     * 给定一个字符串,返回字符串中括号的最大匹配长度
     * @param s
     * @return
     */
    public int getLongestParenthese(String s) {
        char[] ch = s.toCharArray();
        Stack<Integer> stack = new Stack<Integer>();
        int start = -1;
        int max = 0;
        for(int i=0; i<ch.length; i++) {
            if(ch[i] == '(')
                stack.push(i);
            else {
                if(stack.isEmpty()) 
                    start = i;
                else {
                    stack.pop();
                    if(stack.isEmpty()) 
                        max = Math.max(max, i-start);
                    else 
                        max = Math.max(max, i-stack.peek());
                }
            }
        }
        return max;
    }
原文地址:https://www.cnblogs.com/little-YTMM/p/5448741.html