leetcode 32(最长有效的括号匹配子串)

核心:

  标称的动态规划写的很好,状态转移很巧妙; 状态定义:dp[i]-》以第i个字符结尾的最长有效子串长度

我是怎么想的呢? 在整个字符串有有一些无效字符(无法匹配的括号), 无效字符之间就是一段连续有效子串啦。

我们的任务就是用stack找出哪些是无效子串,再找出最长的连续有效字符串~~~~

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    struct node {
        char key;
        int id;
    };
    int longestValidParentheses(string s) {
        stack <node> tack;
        bool isok[s.size()+7]={0};
        for (int i=0;i<s.size();i++) {
            node tmp={s[i], i};
            if (s[i]=='(')
                tack.push(tmp);
            else {
                if (!tack.empty()&&tack.top().key=='(') 
                    tack.pop();
                else
                    tack.push(tmp);
            }
        }
        while (!tack.empty()) { 
            
            node tmp=tack.top();
            isok[tmp.id]=1;
            //printf("%d
",tmp.id);
            tack.pop();
        }
        int ans=0, len=0;
        for (int i=0;i<s.size();i++)  {
            // printf("%d ",isok[i]);
            if (isok[i])
                len=0;
            else {
                len+=1;
                ans=max(ans, len);
            }
        }
        return ans;
    }
};
int main ()
{
    Solution sol;
    string str;
    while (cin>>str) 
        printf("%d
",sol.longestValidParentheses(str));
    return 0;
}
原文地址:https://www.cnblogs.com/xidian-mao/p/11307578.html