Leetcode32 最长有效括号

给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。Leetcode32 最长有效括号_第1张图片

 

Leetcode32 最长有效括号_第2张图片 

 

Leetcode32 最长有效括号_第3张图片 

 Leetcode32 最长有效括号_第4张图片

Leetcode32 最长有效括号_第5张图片 

 代码如下:

class Solution {
    public int longestValidParentheses(String str) {
        Stack s = new Stack<>();
        int res = 0;
        int start = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == '('){
                s.push(i);
            }
            else {
                if(!s.isEmpty()) {
                    s.pop();
                    if(s.isEmpty()){//() () () 
                        res = Math.max(res,i - start + 1);
                    }
                    else {//( ( ( ) ) (
                        res = Math.max(res, i - s.peek());
                    }
                }
                else { // )()()
                    start = i + 1;
                }
            }
        }
        return res;

    }
}

 

 

你可能感兴趣的:(算法,leetcode,职场和发展)