我想写一个递归函数,它递归地从给定的字符串中删除所有重复的字符。 例如“Hello world” - >“Helo wrd”。递归删除重复的字符
我有局限性是:
- 没有循环不允许的。
- 没有更多参数可以添加到原始函数(remove_duplicates)。
- string.h库中没有函数允许,但我可以递归地写入它们。
我被允许使用另一个辅助递归函数。
到目前为止,我写的函数只适用于短字符串,它会多次调用该函数。任何建议如何使它更有效率?
void remove_duplicates3(char string[], int index)//(str,RecursiveStrlen(str, 0)-1)
{
int length = RecursiveStrlen(string + 1, 0);
if (string[index] == '\0' || index == 0)
{
return;
}
if (string[0] != string[index])
{
remove_duplicates3(string, index - 1);
}
else
{
BackspaceString(string, index);
remove_duplicates3(string, length - 1);
}
remove_duplicates3(string + 1, length - 1);
}
int RecursiveStrlen(char str[], int index)
{
if (str[index] == '\0')
return index;
return RecursiveStrlen(str, index + 1);
}
void BackspaceString(char string[],int index)//deletes one char from string in a specific index
{
if (string[index] == '\0')//end of string
return;
string[index] = string[index + 1];
BackspaceString(string, index + 1);
}
边问:你对字符串的长度的限制?因为使用递归如果完成了太多次就会变得很糟糕。 – rbaleksandar
是的,限制是256个字符。 – bar