题意:给出一个串,包含'(',')','#'(至少有一个)三种字符。你需要在'#'处替换为一个或多个')',使得这个串从开头到任何位置,左括号数量不少于右括号,最终左右括号数量相等。
思路:贪心,前面的'#'可以只替换一个右括号,最后一个替换为还需要的数量。难点在于判断不合法的情况,容易坑在最后一个'#'后面出现了不平衡的情况。代码写的比较挫。。。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <string.h>
using namespace std;
#define INF 2e9
char str[100010];
int main(){
while(~scanf("%s",str)){
int len=strlen(str);
int cntl=0;
int cntr=0;
int ok=1;
int cnt=0;
int last=-1;
for(int i=0;i<len;i++){
if(str[i]=='('){
cntl++;
}else if(str[i]==')'){
cntr++;
}else{
cntr++;
cnt++;
last=i;
}
if(cntr>cntl){
ok=0;
break;
}
}
int test=0;
for(int i=last+1;i<len;i++){
if(str[i]=='('){
test++;
}else if(str[i]==')'){
test--;
}
}
if(test>0)ok=0;
int cntl2=0,cntr2=0;
for(int i=0;i<len;i++){
if(str[i]=='('){
cntl2++;
}else if(str[i]==')'){
cntr2++;
}else{
if(i==last){
cntr2+=(1+cntl-cntr);
}else{
cntr2++;
}
}
if(cntr2>cntl2){
ok=0;
break;
}
}
if(!ok){
cout<<"-1"<<endl;
continue;
}
for(int i=1;i<cnt;i++){
printf("1\n");
}
cout<<1+cntl-cntr<<endl;
}
return 0;
}
解决一个包含括号和特殊字符的字符串问题,通过在特殊字符位置插入括号来确保字符串始终保持平衡状态。难点在于判断何时无法使字符串保持平衡。
1939

被折叠的 条评论
为什么被折叠?



