今天看到了一个面试 进去看了看 有个笔试题
给定字符串 ""abcefeddcef",删除指定字符 e 时间复杂度为O(n) 空间复杂度为O(1)
void test()
{
char str[100]="abcefeddcef";
int i=0,j=0;
while(str[i]!='\0')
{
if(str[i]!='e')
{
str[j]=str[i];
i++;
j++;
}
else
{
i++;
}
}
str[j]='\0';
cout<<str<<endl;
}
时间复杂度为O(n) 空间为O(1) 只有多申请了一个j
2.
void test()
{
char str[100]="eeaddeebeecefeeeeddcefee"; //注意一定不能够使用char* str="eeeffadfasdf";由于str指向常量存储区域,这时候是只读的
//不能够修改
int i=0;
int count=0;
while(str[i]!='\0')
{
if(str[i]=='e')
{
count++;
}
else
str[i-count]=str[i];
i++;
}
str[i-count]='\0';
cout<<str<<endl;
}
将指定的字符放在字符串的最后边:
char str[]="**hello***llll**dd";
void repai()
{
int count=0;
for(int n=strlen(str)-1;n>=0;n--)
{
if(str[n]=='*')
{
count++;
}
else
{
str[n+count]=str[n];
}
}
for(int i=0;i<count;i++)
{
str[i]='*';
}
cout<<str<<endl;
}