点击消除字符串

牛牛拿到了一个字符串。
他每次“点击”,可以把字符串中相邻两个相同字母消除,例如,字符串"abbc"点击后可以生成"ac"。
但相同而不相邻、不相同的相邻字母都是不可以被消除的。
牛牛想把字符串变得尽可能短。他想知道,当他点击了足够多次之后,字符串的最终形态是什么?

输入描述:

一个字符串,仅由小写字母组成。(字符串长度不大于300000)

输出描述:

一个字符串,为“点击消除”后的最终形态。若最终的字符串为空串,则输出0。

示例1

输入:abbc

复制输出:ac

输入:abba

输出:0

输入:bbbbb

输出:b

思路:引入栈的数据结构进行完成

  • 引入辅助栈stk,遍历字符串,每次遇到与栈顶相同的字符就栈顶元素出栈
  • 栈为空或者当前字符与栈顶元素不等,就当前元素入栈
  • 输出结果,栈空说明最终是空串,直接输出0
  • 如果不是空串就再引入一个栈来逆置字符输出
#include<stdio.h>
#include <stdlib.h>


struct node {
    char data;
    struct node* next;
};


struct node* xiao_chu(char* p) {
    struct node* tail = malloc(sizeof(struct node));
    tail->next = NULL;
    int i = 0;
    while (*(p + i) != '\0') {
        if (tail->next == NULL) {
            struct node* pnew = malloc(sizeof(struct node));
            pnew->data = *(p + i);
            pnew->next = tail->next;
            tail->next = pnew;

        } else if (tail->next->data != *(p + i)) {
            struct node* pnew1 = malloc(sizeof(struct node));
            pnew1->data = *(p + i);
            pnew1->next = tail->next;
            tail->next = pnew1;
        } else if (tail->next->data == *(p + i)) {
            struct node* l = tail->next;
            tail->next = l->next;
            l->next = NULL;
            free(l);
            l = NULL;

        }


        i++;
    }
    if (tail->next == NULL) {
        printf("0 ");
    } else {
        //引入一个新的栈来逆序输出结果
        //并没有创建新的数据结点,为了最大节省内存空间,选择将原先栈节点按出栈的顺序入栈新的栈
        struct node* tail1 = malloc(sizeof(struct node));
        tail1->next = NULL;
        struct node* f = tail->next;
        while (f != NULL) {
            tail->next = f->next;
            f->next = tail1->next;
            tail1->next = f;
            f = tail->next;
        }
        while (tail1->next != NULL) {
            printf("%c ", tail1->next->data);
            tail1->next = tail1->next->next;
        }



    }

    while (tail->next != NULL) {
        printf("%c ", tail->next->data);
        tail = tail->next;
    }




}


int main() {

    char a[10];
    scanf("%s", a);
    char* pre = a;
    xiao_chu(pre);

}

本人才疏学浅,若有不足欢迎指正!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想学习的朋友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值