题解 | 最长的括号子串

最长的括号子串

https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int longestValidParentheses (String s) {
        // write code here
        if(s == null || s.length() == 0) return 0;
        Stack<Integer> stack = new Stack<>();
        //压入-1作为哨兵,1 - (-1) = 2
        stack.push(-1); 
        int maxLength = 0;
        for(int i = 0;i<s.length();i++){
            int c = s.charAt(i);
            if(c == '(')
            stack.push(i);
            else
            stack.pop();

            if(stack.isEmpty()){
                stack.push(i);//作为新边界
            }
            else
            maxLength = Math.max(maxLength, i - stack.peek());
        }
        return maxLength;
    } 
}

全部评论

相关推荐

02-25 13:02
中南大学 C++
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务