题解 | 最长的括号子串

最长的括号子串

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    int longestValidParentheses(string s) {
        stack<int> stk;
        int ans = 0;
        for (int i = 0, start = -1; i < s.size(); i++) {
            if (s[i] == '(') stk.push(i);
            else {
                if (!stk.empty()) {
                    stk.pop();
                    if (!stk.empty()) {
                        ans = max(ans, i - stk.top());
                    } else {
                        ans = max(ans, i - start);
                    }
                } else {
                    start = i;
                }
            }
        }
        return ans;
    }
};

全部评论

相关推荐

09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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