c - Recursively removing duplicate characters in a string
问题描述
I'm trying to create a recursive function which removes the consecutive duplicate characters from a string. It works fine except the first few characters. For example if my input is MMMMMuuuuuOOOOOKKKKLLLEE OOOOLLL
or something like this, output is MMuOKLE OL
. As you can see except for the first two M's it works fine. How can I make this work for the first part too?
Here is my code:
#include <stdio.h>
char* remove_duplicates (char* str){
if(*(str+1)!='\0'){
if(*str==*(str+1)){
*(str+1)=*(str+2);
remove_duplicates(str+1);
}
remove_duplicates(str+1);
}
return str;
}
int main()
{
char sample[] = "MMMMMuuuuuOOOOOKKKKLLLEE OOOOLLL";
printf("OLD: |%s|\n", sample);
printf("NEW: |%s|\n", remove_duplicates(sample));
return 0;
}
解决方案
给你。
#include <stdio.h>
char * remove_duplicates( char *s )
{
if ( *s )
{
if ( *s == *( s + 1 ) )
{
*( s + 1 ) = *( s + 2 );
remove_duplicates( s + 1 );
remove_duplicates( s );
}
else
{
remove_duplicates( s + 1 );
}
}
return s;
}
int main(void)
{
char s[] = "MMMMMuuuuuOOOOOKKKKLLLEE";
remove_duplicates( s );
puts( s );
return 0;
}
程序输出为
MuOKLE
推荐阅读
- c++ - 为什么这个构造函数没有给出不完整的类型错误?
- python - Django模板标签将GET参数从当前请求添加到Python3+Django2中的url
- docker - 将 dockerized Spring Cloud Netflix 项目部署到 Kubernetes
- css - 导航栏品牌问题
- php - 将唯一迭代器附加到脚本中的 div id
- sql - 是否可以将这两个查询与 SQLite 中的连接结合起来?
- azure-service-fabric - Service Fabric,正常关闭“旧”服务实例
- django - 我们如何在 django 管理搜索字段中搜索多对多字段
- android - 注册广播接收器后更新意图过滤器
- compression - 为什么即使所有数据集都压缩在文件中,压缩 HDF5 文件仍能获得大量压缩?