删除多余空格与代码的优化

在一个字符串中若有一个或者多个连续空格组成,将其改为单个空格字符
字符代码如下:
1.
void DelBlank1(char *str)
{
for(int i=0;str[i]!=’\0’;i++)//bug
{
if(str[i]’ ’ && str[i+1]’ ‘) //删除str[i+1]的空格
{
for(int j=i+1;str[j]!=’\0’;j++) //’\0’也被置换到了字符串最后
{
str[j] = str[j+1];
}
}
}
}

int main()
{
char str[]="dfa fda "
DelBlank1(str);
return 0;
}
总结:时间复杂度O(n^2),空间复杂度O(1) 代码存在bug:连续两个以上的空格只能删除一个空格
优化1:将代码的时间复杂度优化为O(n),空间复杂度为O(n)且修复bug
代码如下:
2.
void DelBlank2(char *str)
{
char *buf = (char )malloc(sizeof(char)(strlen(str)+1)); //strlen没有算上’\0’ 所以要加1
int i = 0;
int j = 0;
while(str[i]!= ‘\0’)
{
if(str[i]’ ’ && str[i+1]’ ')
{
i++;
}
else
{
buf[j++] = str[i++];
}
}
buf[j] = ‘\0’;
strcpy(str,buf);
free(buf);
}

int main()
{
char str[]="dfa fda "
DelBlank1(str);
return 0;
}
总结:时间复杂度为O(n) 空间复杂度为O(n)且无bug
优化2:将其时间复杂度优化为O(n) 空间复杂度为O(1)
代码如下:
void DelBlank(char *str)//O(n),O(1)
{
int i = 0;//当前需要往前挪动数据的下标
int j = 0;//当前可以存放数据的下标
while(str[i]!= ‘\0’)
{
if(str[i]’ ’ && str[i+1] ’ ')
{
i++;
}
else
{
str[j++] = str[i++];
}
}
str[j] = ‘\0’;
}

int main()
{
char str[]="dfa fda "
DelBlank(str);
return 0;
}

总结:时间复杂度为O(n)空间复杂度为O(1),优化成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值