给定仅由''和''组成的字符串S,找出最长的有效子字符串的长度

问题描述

我知道在stackoverflow上已经对此有疑问,但是我的代码是不同的。所以我用堆栈来解决这个问题,但是以某种方式我的输出就不能正确输出,但是当我尝试使用给出错误输出的输入测试用例在纸上解决这个问题时,我能够得到正确的答案,我缺少什么代码还是哪里错了?

错误输出的测试用例-))))))()()))(())))())((()()()())((((()))())

我的输出-6,预期输出-20

我的代码-

#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main() {
    //code
    int tc,count,max;
    cin>>tc;
    while(tc--){
        string s;
        cin>>s;
        max = 0;
        count = 0;
        stack<char> store;
        int len = s.size();
        for(int i=0;i<len;i++){
            if(s[i] == '(') store.push(s[i]);
            else{
                if(!store.empty() && store.top() == '('){
                    count+= 2;
                    store.pop();
                }else if(count>max){
                    max = count;
                    count = 0;
                }
            }
        }
        cout<<max<<"\n";
    }
    return 0;
}

解决方法

在这段代码中:

if(!store.empty() && store.top() == '(') {
     count+= 2;
     store.pop();
} else if(count>max) {
     max = count;
     count = 0;
}

请考虑当最长有效子字符串位于字符串末尾时会发生什么:您永远不会点击false分支,因此永远也不会更新max。对代码的最小更改可能是:

if(!store.empty() && store.top() == '(') {
     count+= 2;
     store.pop();
     if(count>max) {
         max = count;
     }
} else {
     count = 0;
}

每次max更改时,您要在count上进行更新。

可以对代码进行更多简化,例如由于stack仅包含相同的值,因此您可以将其替换为int