32. Longest Valid Parentheses

来源:互联网 发布:卸载加密软件 编辑:程序博客网 时间:2024/06/07 05:15

Description:

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.


简要题解:

从左到右开始统计,无论何时左括号的数量一定都大于或等于右括号的数量。

类似地,从右到左开始统计,无论何时右括号的数量一定都大于或等于左括号的数量。

可以先从左边开始顺序地向右移动,计算出所有有效括号子串的长度,不断更新“当前最大长度”。

由于缺乏对称性,所以想要遍历所有情况必须再从右往左计算一遍。原理类似。最后得出的“当前最大长度”就是所要求的最大长度。


代码:

class Solution {public:    int longestValidParentheses(string s) {        int maxLength = 0, l = 0, r = 0;        for (int i = 0; i < s.size(); i++) {            if (s[i] == '(')                l++;            else                r++;            if (l == r)                maxLength = (l + r > maxLength) ? l + r : maxLength;            if (l < r)                l = r = 0;        }                l = r = 0;        for (int i = s.size() - 1; i >= 0; i--) {            if (s[i] == '(')                l++;            else                r++;            if (l == r)                maxLength = (l + r > maxLength) ? l + r : maxLength;            if (l > r)                l = r = 0;        }        return maxLength;    }};


原创粉丝点击