递归反向字符串Java

递归反向字符串Java,java,string,recursion,Java,String,Recursion,我尝试在Java中递归地反转字符串,但我只得到最后一个字符作为输出 我在网上查了一下,大多数代码都修改了输入字符串。我试图将输出从空字符串构建为反向字符串。请告诉我我的程序出了什么问题 class reverseStringRecursion { public static void main(String args[]) { System.out.println(reverse()); } public static String revers

我尝试在Java中递归地反转字符串,但我只得到最后一个字符作为输出


我在网上查了一下,大多数代码都修改了输入字符串。我试图将输出从空字符串构建为反向字符串。请告诉我我的程序出了什么问题

class reverseStringRecursion
{
    public static void main(String args[])
    {
        System.out.println(reverse());
    }

    public static String reverse()
    {
        String strInput = " Hello I am my name.";
        String output = "";
        return recursiveHelper(strInput, 0, output);
    }

    public static String recursiveHelper(String strInput, int index, String output)
    {
        if(index == (strInput.length() - 1 ))
            output += strInput.charAt(index) + "";
        else
            output+= recursiveHelper(strInput, index + 1, output) +"";

        return output;
    }
}

上面的代码只返回输出“.”,其他什么都不返回。请提供帮助。

由于
strInput
始终包含原始字符串,以下条件确保您的代码只接受该字符串的最后一个字符,而忽略所有其他字符:

if(index == (strInput.length() - 1 ))
    output += strInput.charAt(index) + "";
要以递归方式构建反转字符串,必须将字符串的最后一个字符附加到第一个长度为()-1个字符的子字符串的背面

这意味着您不需要方法的第2个和第3个参数,在每次递归调用中,
strInput
应该传递一个较短的
字符串

public static String reverse (String strInput)
{
    if(strInput.length() <= 1)
        return strInput;
    else
        return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}
公共静态字符串反转(字符串strInput)
{

如果(strInput.length()因为
strInput
始终包含原始字符串,则以下条件确保您的代码只接受该字符串的最后一个字符,而忽略所有其他字符:

if(index == (strInput.length() - 1 ))
    output += strInput.charAt(index) + "";
要以递归方式构建反转字符串,必须将字符串的最后一个字符附加到第一个长度为()-1个字符的子字符串的背面

这意味着您不需要方法的第2个和第3个参数,在每次递归调用中,
strInput
应该传递一个较短的
字符串

public static String reverse (String strInput)
{
    if(strInput.length() <= 1)
        return strInput;
    else
        return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}
公共静态字符串反转(字符串strInput)
{

如果(strInput.length()因为Java中的
String
是不可变的,那么在这种情况下,通过参数传递它是无用的,所以我删除了它

public class Main {
    public static void main(String args[]) {
        System.out.println(reverse());
    }

    public static String reverse() {
        String strInput = " Hello I am my name.";
        return recursiveHelper(strInput, 0);
    }

    public static String recursiveHelper(String strInput, int index) {
        String output;
        if(index == (strInput.length() - 1 )){
            output = strInput.charAt(index) + "";
        }else{
            output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
        }
        return output;
    }
}

因为Java中的
字符串是不可修改的,所以在这种情况下,通过参数传递它是无用的,所以我删除了它

public class Main {
    public static void main(String args[]) {
        System.out.println(reverse());
    }

    public static String reverse() {
        String strInput = " Hello I am my name.";
        return recursiveHelper(strInput, 0);
    }

    public static String recursiveHelper(String strInput, int index) {
        String output;
        if(index == (strInput.length() - 1 )){
            output = strInput.charAt(index) + "";
        }else{
            output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
        }
        return output;
    }
}

其他人已经很好地解释了为什么您的代码不工作。为了进行比较,这里有一个工作版本,其中有一些注释:

public static void main(String args[])
{
    System.out.println(reverse("Hello I am my name."));
}

public static String reverse(String text)
{
    // Base case:
    // If the string is empty, we're done.
    if (text.length() == 0) {
        return "";
    } else {
        // reverse("hello") = reverse("ello") + "h"
        return reverse(text.substring(1)) + text.charAt(0);
    }
}

其他人已经很好地解释了为什么您的代码不工作。为了进行比较,这里有一个工作版本,其中有一些注释:

public static void main(String args[])
{
    System.out.println(reverse("Hello I am my name."));
}

public static String reverse(String text)
{
    // Base case:
    // If the string is empty, we're done.
    if (text.length() == 0) {
        return "";
    } else {
        // reverse("hello") = reverse("ello") + "h"
        return reverse(text.substring(1)) + text.charAt(0);
    }
}
修改您的类:

public class ReverseStringRecursion {

    public static void main(String args[])
    {
        System.out.println(reverse());
    }

    public static String reverse()
    {
        String strInput = "My Name is Jane Doe";
        String output = "";
        return recursiveHelper(strInput,0);
    }

    public static String recursiveHelper(String strInput, int index)
    {
        if(index == (strInput.length() - 1 ))
            return "" + strInput.charAt(index) ;
        else 
            return recursiveHelper(strInput,index+1) + strInput.charAt(index);
    }
}
修改您的类:

public class ReverseStringRecursion {

    public static void main(String args[])
    {
        System.out.println(reverse());
    }

    public static String reverse()
    {
        String strInput = "My Name is Jane Doe";
        String output = "";
        return recursiveHelper(strInput,0);
    }

    public static String recursiveHelper(String strInput, int index)
    {
        if(index == (strInput.length() - 1 ))
            return "" + strInput.charAt(index) ;
        else 
            return recursiveHelper(strInput,index+1) + strInput.charAt(index);
    }
}

我会将您的函数recursiveHelper()更改为只接收一个参数(要反转的字符串)

public static String recursiveHelper(String strInput) {
    if(strInput.length() == 1) {
        return strInput;
    }
    else if(strInput == "") {
        return "";
    }

    String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2));    // Here we copy the first half of the String to another String
    String subString2 = recursiveHelper(strInput.substring(strInput.length()/2));    // Here we do the same, but with the second half of the original String

    return susbString2 + subString1;    // It is very important that you sum the two substrings in this order!
}

我会将您的函数recursiveHelper()更改为只接收一个参数(要反转的字符串)

public static String recursiveHelper(String strInput) {
    if(strInput.length() == 1) {
        return strInput;
    }
    else if(strInput == "") {
        return "";
    }

    String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2));    // Here we copy the first half of the String to another String
    String subString2 = recursiveHelper(strInput.substring(strInput.length()/2));    // Here we do the same, but with the second half of the original String

    return susbString2 + subString1;    // It is very important that you sum the two substrings in this order!
}
1) 基本情况 如果左>=右-什么也不做

2) 否则交换s[left]和s[right},并调用helper(left+1,right-1)]

类解决方案{
公共无效反向限制(字符[]s){
int left=0,right=s.length-1;
while(左<右){
char tmp=s[左];
s[left++]=s[right];
s[右--]=tmp;
}
}
}

1)基本情况 如果左>=右-什么也不做

2) 否则交换s[left]和s[right},并调用helper(left+1,right-1)]

类解决方案{
公共无效反向限制(字符[]s){
int left=0,right=s.length-1;
while(左<右){
char tmp=s[左];
s[left++]=s[right];
s[右--]=tmp;
}
}

}

我建议使用IDE的调试器。你可以一步一步地浏览代码,看看你的逻辑哪里出了问题。“大多数代码都修改了输入字符串”。不太可能,java字符串是不可变的。您的代码除了最后一个字符外,从不向输出中添加任何内容。请注意,您只为最后一个字符调用了
charAt()
。要反转字符串,您也可以使用
new StringBuilder(“文本”)。反转()。toString()
StackOverflow不用于您的计算机科学作业:-(我建议您使用IDE的调试器。您可以逐步检查代码,看看逻辑哪里出了问题。“大多数代码都修改了输入字符串”。java字符串不太可能是不变的。您的代码除了最后一个字符外,从不向输出添加任何内容。请注意,您正在调用
charAt()
仅用于最后一个字符。若要反转字符串,您也可以使用新的StringBuilder(“文本”)。反转()。toString()
StackOverflow不用于计算机科学作业:-(@smartx感谢你给出了清晰的答案。你能解释一下反向方法是如何循环直到字符串完全反转的吗?我的意思是这里没有任何循环。函数是,这意味着它调用自己。函数的最后一行是
return reverse(…);
,因此它不断地反复调用自己。这就是“循环”好的。那么它怎么知道什么时候结束?它在哪里保存当前重复的值?基本情况是结束。如果字符串为空,那么函数不会再次调用自己。值不必显式地保存在任何地方…正如注释所说,如果字符串为“hello”,我们只需执行
reverse(“ello”)+“h”
。当递归调用发生时,
“h”
在那里等待。一旦递归调用返回“olle”,则“h”会一直停留在末尾,我们得到“olleh”@smartx谢谢你的明确回答。你能解释一下反向方法是如何循环直到字符串完全反转的吗?我的意思是这里没有任何循环。函数是,这意味着它调用自己。函数的最后一行是
return reverse(…);
,所以它不断地调用自己。这就是“循环”好的。那么它怎么知道什么时候结束?它在哪里保存当前重复的值?基本情况是结束。如果字符串为空,那么函数不会再次调用自己。值不必显式地保存在任何地方…正如注释所说,如果字符串为“hello”,我们只需执行
reverse(“ello”)+“h”
。当递归调用发生时,
“h”
在那里等待。