// 空间复杂度O(1),时间复杂度O(n)
void str_unique(char* str, int fs, int fd, int ed)
{
if (fs> (int)strlen(str)) return;
// skip extra whitespace
while(str[fs]==' ')++fs;
// find word [fs, es], contain ' ' or '\0' in the end
int es=fs;
while(1)
{
if(str[es]==' ' || str[es]=='\0') break;
else ++es;
}
// compare
bool flag = true;
for (int i = fs; i <= es; ++i)
{
if (str[i] != str[fd+i-fs])
{
flag = false;
break;
}
}
// move
if (!flag || ed==-1)
{
for (int i = fs; i <= es; ++i)
{
str[ed+i-fs+1] = str[i];
}
fd = ed+1;
ed = fd+es-fs;
}
// next
fs = es+1;
str_unique(str, fs, fd, ed);
}
void my_str_unique(char* str)
{
str_unique(str, 0, 0, -1);// ed=-1,skip the first whitespace in the front of the string
}
int _tmain(int argc, char* argv[])
{
char str[] = " hello hello hello my my summer ";
my_str_unique(str);
cout<<str<<endl;
return 0;
}
去掉字符串相邻重复单词
最新推荐文章于 2024-06-14 09:26:00 发布