题解 | #最长的括号子串#

最长的括号子串

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
        int res = 0;
        int start = -1;
        Stack<Integer> st = new Stack<>();
        for(int i = 0; i < s.length();i++){
            if(s.charAt(i) == '('){
                st.push(i);
            }else{
                if(st.isEmpty()){
                    start = i;
                }else{
                    st.pop();
                    if(!st.isEmpty()){
                        res = Math.max(res,i - st.peek());
                    }else{
                        res = Math.max(res,i - start);
                    }
                }
            }
        }
         return res;
    }
}

全部评论

相关推荐

12-11 14:24
门头沟学院 Java
牛客35720396...:不要用boss,全是骗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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