其他分享
首页 > 其他分享> > 最少次将无规则括号进行转化成正确括号对

最少次将无规则括号进行转化成正确括号对

作者:互联网

int longestValidParentheses(string s) {
    int l = 0, r = 0, ans = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(')l++;
        else r++;
        if (r > l)l = r = 0;
        else if (r == l)ans = max(ans, 2 * r);
    }
    l = r = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        if (s[i] == ')')l++;
        else r++;
        if (r > l)l = r = 0;
        else if (r == l)ans = max(ans, 2 * r);
    }
    return ans;
}

int main()
{
    int n;
    int b;
    cin >> n;
    cin    >> b;
    string s;
    cin >> s;

    //string s = "))(((())()()()())(";

    cout << (b - longestValidParentheses(s)) / 2;

}

题解::先找到最长括号对,然后剩下的除以二

标签:转化成,cin,int,++,else,括号,无规则,ans,string
来源: https://www.cnblogs.com/221lin/p/15225256.html