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

最长的括号子串

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

class Solution {
public:
    int longestValidParentheses(string s) {
        int n=s.size();
        int cnt = 0;
        int max = 0;
        vector<int> st;
        string strip(n, ' ');
        int i = 0;
        for (auto c:s) {
            if (c == '(') {
               st.push_back(i);
            }
            else {
                if(!st.empty()) {
                    auto left = st.back();
                    st.pop_back();
                    strip[i] = ')';
                    strip[left] = '(';               
                }
            }
            i++;
        }
        for (auto c:strip) {
            if (c != ' ') {
                cnt++;
            }
            else {
                max = max<cnt ? cnt : max;
                cnt = 0;
            }
        }
        if (cnt) max = max<cnt ? cnt : max;
        return max;
    }
};

就输出所有合法的括号匹配,用同样长度字符串来存放,不合法位置默认用空格,
这样从前往后找最长的一串就是最大长度

全部评论

相关推荐

10-13 16:58
门头沟学院 Java
面了100年面试不知...:一周七天,一天去一家上班😍😍😍
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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