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.

这题就是求最长的匹配成功的括号个数。
右括号会和前边最近的左括号进行匹配。把左括号压栈,就是和栈顶的匹配。用一个和string一样长的vector去标记每个括号是否匹配成功。遍历整个string,左括号就把括号的下标压进去,要是右括号就进行匹配,匹配成功,返回的匹配成功的左括号的下标,并把这对左括号和右括号分别标记为1。匹配失败标志位是0不用动,接着往下走。
一遍匹配之后就数最长的连续的1有多少个。
建个变量保存最大值。用一个变量当计数器,多一个1就加1,遇到0就把计数器清0。最大值就是结果。
代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.size();
        vector flag(len,0);
        vector indexs;
        for(int i = 0; s[i] != '\0'; i++)
        {
            if(s[i] == '(')//左括号压索引
                indexs.push_back(i);
            else if(s[i] == ')')
            {
                int r = pipei(indexs);
                if(r == -1)
                    flag[i] = 0;    
                else 
                {
                    flag[i] = 1;
                    flag[r] = 1;
                }
            }    
        }
        int count = 0;
        int maxValue = 0;
        for(int i = 0;i< flag.size();i++)
        {
            if(flag[i] == 0)
             count=0;
            else 
            {
                count++;
                if(maxValue < count)
                    maxValue = count;
            }
        }
        return maxValue;      
    }
private:
    //成功返回匹配的索引 不成功返回-1 
    int pipei(vector &indexs)
    {
        if(indexs.size() == 0)
            return -1;
        int res = indexs[indexs.size()-1];
        indexs.pop_back();
        return res;  
    } 
};

你可能感兴趣的:(32. Longest Valid Parentheses 笔记)