先理解一下伪代码是干什么的。
可以理解为 初始在 的位置是 ,从前往后 + 就是 ,- 就是 ,如果 了就把初始位置的值 ,统计全部移动的距离。
可以发现 了相当于移动的距离加上现在的位置 ,可以避免这一层循环,从而让复杂度正确。
注意字符串的偏移,以及要开 long long。
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--){
string str;
cin>>str;
int m=str.size();
long long cnt=0,ans=m;
for(int i=0;i<m;i++){
if(str[i]=='+') cnt++;
else cnt--;
if(cnt<0){
ans=ans+i+1;
cnt++;
}
}
cout<<ans<<"\n";
}
return 0;
}本文使用 ChatGPT 辅助检查错别字并规范 Markdown、LaTeX 排版。