我想寫一個遞歸函數,它遞歸地從給定的字符串中刪除所有重複的字符。 例如「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