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;
}
Run Code Online (Sandbox Code Playgroud)
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.
我会尝试一下。
递归解决方案的一般思想是每次调用都获得一个指向字符串开头的指针,以及要查看的字符数,这会走到字符串的中间。
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);
}
Run Code Online (Sandbox Code Playgroud)
每次递归调用时,起始字符串指针加一,长度减二。
FIRST CALL: v v
hello, world
SECOND CALL: ^ ^
Run Code Online (Sandbox Code Playgroud)
常见的危险区域是确保它对偶数和奇数长度的字符串做正确的事情。
这种方法更简单,只有两个参数,而且 - 正如有些人可能会说的 - 更优雅 :-) 即使++和--可能被认为是棘手的(一个增量和两个减量)。
编辑:这个版本也是尾递归的,它可以通过内部将其转换为循环来导致某些优化。