Leetcode Difficulty - Longest Valid Parentheses (Super Detailed Ideas)

(I feel that the difficulty of Lituo is fascinating. Sometimes it requires a particularly clever idea, and sometimes it is a very simple question)

Problem:
Given a string containing only '(' and ')', find the length of the longest valid (well-formed and consecutive) parenthesis substring.

Solution:
Pay attention to the continuity mentioned in the title, how should we think about it?

Each ")" matches the previous "(" and the corresponding two can be deleted, because these two will not affect the subsequent ")" match, and each match must be continuous in the middle (or It was originally posted, or the one in the middle is a match and deleted)

Then every time you match, just judge the length of the current continuous string length
= the index of the currently matched ")" - the index of the parenthesis that was not deleted in front of "("
(why not subtract the previous "( "The index, because there is a situation "()()", so you can only get 2)

For the convenience of calculation, we can add a ")" at the front, and the index is -1, because it is not sure that it will not match, so it will not affect the result. For example, ")()()" At this time, we match the last two
parentheses "()" is the index 3 - (-1) (the index starts from -1, of course it is also possible to write it as starting from 0)

code show as below:

class Solution {
public:
    vector<pair<bool, int> > ddd;
    int longestValidParentheses(string s) {
        int res = 0;
        ddd.push_back(make_pair(true, -1));
        for(int i = 0; i < s.size(); i++) {
            if(s[i] == '(') ddd.push_back(make_pair(false, i));
            else ddd.push_back(make_pair(true, i));
        }
        for(int i = 2; i < ddd.size(); i++) {
            if(ddd[i].first && !ddd[i - 1].first) {
                res = max(res, ddd[i].second - ddd[i - 2].second);
                ddd.erase(ddd.begin() + i - 1, ddd.begin() + i + 1);
                i = i - 2;
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/m0_52212261/article/details/128890585