问题
There is this problem on LeetCode that I can not get to work in C/C++
The idea is to reverse an array in its place (using no other additional array) using recursion.
The link is : https://leetcode.com/explore/learn/card/recursion-i/250/principle-of-recursion/1440/
The solution is done in Java or Python.
I tried implementing the solution in C but I always get the original array, my code is as follows:
void reverseString(char* s, int sSize){
if(!s)
return;
reverseString(s+1,sSize-1);
s[sSize] = *s;
}
There is something I am not accounting for. Please let me know how would you solve it, and if possible why this is not working. Thanks.
回答1:
I'll take a stab at this.
The general idea for a recursive solution is for each call to get a pointer to the start of a string, and how many characters to look at, and this walks its way to the middle of the string.
void reverseString(char *start, int n)
{
if (n <= 1) return;
char tmp = start[0];
start[0] = start[--n]; // the nth character is start[n-1]
start[n] = tmp;
reverseString(++start, --n);
}
On each recursive call, the starting string pointer is incremented by one, and the length decreased by two.
FIRST CALL: v v
hello, world
SECOND CALL: ^ ^
The common danger area is making sure it does the right thing with even and odd-length strings.
This method is a bit simpler with just two parameters, and - as some might say - a bit more elegant :-) even if the ++
and --
could be considered tricky (one increment and two decrements).
EDIT: This version is also tail recursive, which can lead to certain optimizations by internally turning it into a loop.
回答2:
Solution (thank you to the folks in the comments):
void reverse(char * str, int len)
{
char tmp;
if (len <= 1)
return;
tmp = str[0];
len--;
str[0] = str[len];
str[len] = tmp;
str++;
reverse(str, len-1);
}
Call this function with your initial string and 0 as arguments:
char str[] = "Ding dong";
reverse(str, 0, strlen(a));
回答3:
void reverse_string(char *x, int start, int end)
{
char ch;
if (start >= end)
return;
ch = *(x+start);
*(x+start) = *(x+end);
*(x+end) = ch;
//Function calling itself: Recursion
reverse_string(x, ++start, --end);
}
In this function we are passing the string, the starting index and the ending index.... The recursion will continue till start>=end
i.e. till the center of the string appears..... And everytime it will swap the 2 indexes i.e. from the start and from the end...
来源:https://stackoverflow.com/questions/59438783/flip-array-recursively