32. Longest Valid Parentheses

一、题目

  1、审题

  

  2、分析:

    一个只包含‘(‘、’)’的字符串,求其中正确闭合的子串的最大长度。

二、解答

  1、思路:

    方法一:

      从第一个字符开始遍历,依次求出从遍历的字符开始的最长闭合的字符串长度,从而记录最长闭合的字符串长度。

class Solution {
    public int longestValidParentheses(String s) {

        int slen = s.length();
        if (slen == 0)
            return 0;

        int maxLen = 0;
        for (int i = 0; i < slen - 1 - maxLen; i++) {  // 从第一个字符开始,依次遍历
            int count = 1;                // 记录是否闭合
            if(s.charAt(i) == ')')
                continue;
            int tmpLen = 0;  
            int leftLen = 1;          // '(' 的个数
            for (int j = i+1; j < slen; j++) {
                if(s.charAt(j) == '(') {  
                    count++;
                    leftLen++;
                }
                else {
                    count--;
                }
                if(count < 0)
                    break;
                if(count == 0)  
                    tmpLen = leftLen * 2;

            }

            if(tmpLen > maxLen)
                maxLen = tmpLen;
        }
        return maxLen;
    }
}

  

  方法二:

    用 Stack 存放 '(' 的下标,碰到 ‘)’只需要栈顶减去此时的下标即为与此‘)’匹配的子串长度,同时对每一个闭合的子串长度加以记录,统计出最大的字符串长。

public class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        int target = 0;
        int  left = -1;   // 记录 '(' 的下标

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '(')
                stack.push(i);
            else {
                if(stack.isEmpty()){
                    left = i;
                }else {
                    stack.pop();
                    if(stack.isEmpty()) target = Math.max(target, i - left);
                    else                target = Math.max(target, i - stack.peek());
                }
            }
            
        }
        return target;
    }
}            

 

posted @ 2018-08-07 23:11  skillking2  阅读(96)  评论(0编辑  收藏  举报