题目:实现 void delete_char(char * str, char ch);
把str中所有的ch删掉
解析:最容易想到的算法是遍历字符串,找到目标,删掉后对后面的元素进行移位,这样算法的复杂度是O(n^2),
不是最优方法,我下面的方法的复杂度为O(n),是线性时间,实现如下
#include <cstdio>
#include <cstring>
void delete_char(char * str, char ch)
{
char * deleteCh = NULL;
int sLen = strlen(str);
char* s = str;
for(int i=0;i<sLen;++i)
{
if (*s == ch)
{
if(deleteCh==NULL)
deleteCh=s;
}
else
{
if(deleteCh!=NULL)
{
*deleteCh = *s;
deleteCh++;
}
}
s++;
}
*deleteCh = '\0';
}
int main()
{
char a[] = "abscdbfg";
printf("%s\n",a);
delete_char(a,'b');
printf("%s\n",a);
}