I'm trying to write a recursive function which remove all duplicate chars from a given string recursively.
For example "Hello world" -> "Helo wrd".
The limitations I have are:
- No loops allowed.
- No more arguments can be added to the original function (remove_duplicates).
- No functions from string.h library allowed, although I'm allowed to write them recursively.
I'm allowed to use another auxiliary recursive functions.
The function I wrote so far works only for short strings, it calls the function too many times. Any recommendations how to make it more efficient?
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);
}
Answer
Pure recursive solution:
void remove_char(char string[], char c, int read_index, int write_index) {
if (string[read_index] == 0) {
string[write_index] = 0;
return;
}
if (c == string[read_index]) {
remove_char(string, c, read_index + 1, write_index);
} else {
string[write_index] = string[read_index];
remove_char(string, c, read_index + 1, write_index + 1);
}
}
void remove_duplicates(char string[], int index) {
if (string[index] != 0 && string[index + 1] != 0) {
remove_char(string, string[index], index + 1, index + 1);
remove_duplicates(string, index + 1);
}
}
No comments:
Post a Comment