我想編寫一個代碼,用於從字符串中刪除給定的字符。我想出了以下代碼片段。刪除字符串中的字符
現在,雖然這是我的工作,但它給我的最壞情況複雜度爲O(n^2)。任何人都可以幫助我改善這一點。
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void Push(char *, int i);
int n=6;
int main()
{
clrscr();
char *p = "helelo";
char delChar = 'e';
for(int i=0;i<5;i++)
{
if(*(p + i) == delChar)
{
Push(p, i);
}
}
cout<<p<<endl;
getch();
return 1;
}
void Push(char *p, int i)
{
for(int k=i;k<n;k++)
{
*(p + k) = *(p+k+1);
}
}
由於
你應該在列表中走一次,當你發現你W上的字符螞蟻刪除,從這一點一步一步通過列表,但像你這樣複製下一個元素到當前的元素。另外,爲什麼不使用'std :: string'/char數組,而不是執行'p [k]'而不是手動建立索引,並返回1(0表示成功)? – GManNickG 2010-10-31 04:51:18