LeetCode 32.Longest Valid Parentheses

题目:

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.

分析与解答:跟Generate Parentheses 这个问题很类似。从下标为Index的地方开始进栈。遇到'('就将下标进栈,遇到')'时,如果栈为空就跳过,否则就弹出栈顶元素。弹出后判断栈是否为空,如果为空就用当前值减去Index计算合理序列长度。当然了,会出现两个合理序列是相邻的情况,做个标记即可。

class Solution {
public:
int longestValidParentheses(string s) {
    int result = 0, left = -1;
    vector<int> stack;
    for(int i = 0; i < s.size(); ++i) {
        if(s[i] == '(') {
            stack.push_back(i);//将下标进栈
        } else {
            if(stack.empty())   //如果栈为空,则跳过
                left = i;
            else {//如果栈不为空,则弹出栈顶元素并更新result
                stack.pop_back();
                if(stack.empty()) //弹出元素之后栈为空
                    result = max(result, i - left);
                else
                    result = max(result, i - stack.back());
            }
        }
    }
    return result;
}
};


其实此题有空间复杂度为O(1)的解法,正向和反向两遍扫描即可。别人的代码:

class Solution {
  public:
    int longestValidParentheses(string s) {
        int answer = 0, depth = 0, start = -1;
        for(int i = 0; i < s.size(); ++i) {
            if(s[i] == '(')
                ++depth;
            else {
                --depth;
                if(depth < 0) {
                    start = i;
                    depth = 0;
                } else if(depth == 0)
                    answer = max(answer, i - start);
            }
        }
        depth = 0;
        start = s.size();
        for(int i = s.size() - 1; i >= 0; --i) {
            if(s[i] == ')')
                ++depth;
            else {
                --depth;
                if(depth < 0) {
                    start = i;
                    depth = 0;
                } else if(depth == 0)
                    answer = max(answer, start - i);
            }
        }
        return answer;
    }
};



你可能感兴趣的:(String)