题解 | 点击消除
点击消除
https://www.nowcoder.com/practice/8d3643ec29654cf8908b5cf3a0479fd5
#include <stdio.h>
#include<string.h>
int main() {
int top=-1;
char s[300000];
char last[300000];
scanf("%s",s);
for(int i=0;i<strlen(s);i++){
if(top==-1||last[top]!=s[i]){
top++;
last[top]=s[i];
continue;
}
else if(last[top]==s[i]){
top--;
}
}
char put_out[300000];
strncpy(put_out, last, top+1);
put_out[top+1]='\0';
if(top<0){
printf("0");
}
else{
printf("%s",put_out);
}
return 0;
}
本题为简单的入栈出栈问题,定义一个数组用来作为栈,定义一个top指针;思路为将遍历输入的字符串中,如果栈为空或栈顶字符与当前遍历到的字符不同则入栈,如果栈顶字符和当前遍历到的字符相同则出栈(top--),将最后栈中的字符串top指针以下的字符串输出。
