0
点赞
收藏
分享

微信扫一扫

二、软件工程——Modeling

云卷云舒xj 2023-06-02 阅读 44

每日一题

删除字符串中的所有相邻重复项

题目链接

在这里插入图片描述

思路

实现代码

char * removeDuplicates(char * s){
    int len = strlen(s);
    
    char* stack = (char *)malloc(sizeof(char) * (len + 1));	//申请返回的字符串的内存
    int top = 0;	//栈顶指针置零
    
    for(int i = 0; i < len; i++)
    {
        //如果栈不为空或遍历元素等于栈顶元素,出栈
        if(top > 0 && s[i] == stack[top - 1])
            top--;
        //否则,入栈
        else
            stack[top++] = s[i];
    }
    
    stack[top] = 0;	//确定新字符串结束位置
    
    return stack;	//返回新的字符串
}
举报

相关推荐

0 条评论