2020年7月4日打卡

    技术2025-12-04  27

    Leetcode 32. 最长有效括号

    题目

    给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。 如:“)()()”, “()((())”

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-valid-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    想法及思路

    首先说到括号的匹配就优先想到栈,通过读入左括号当遍历到右括号时弹出的方法进行统计括号的数量,但是本题要求的是最长有效字串的长度,故需标记所有合法括号然后统计,我采用的是将字符串内合法的括号均转换为字母 a ,然后统计最大连续 a 的长度。

    int longestValidParentheses(string s) { int count = 0, max = 0; stack<int> pos; for(int i = 0; i < s.size(); i++){ if(s[i] == '('){ pos.push(i); }else if(!pos.empty()){ s[pos.top()] = 'a'; s[i] = 'a'; pos.pop(); } } for(int i = 0; i < s.size(); i++){ if(s[i] == 'a'){ count++; }else{ max = max > count ? max : count; count = 0; } } max = max > count ? max : count; return max; }

    本来还想写点,睡了睡了,不写了

    Processed: 0.019, SQL: 9