繁体   English   中英

使用递归反转字符串

[英]Using Recursion to Reverse a String

我正在尝试使用递归逐字反转字符串。 (例如:“你好我的朋友”被颠倒为“朋友我的你好”)这是我试图为这个方法编写的代码。 我尝试了多个类似的变体,但输出只是字符串的第一个或最后一个单词。 我相信“损坏”的部分是第一个 if 语句,但我不太确定。

public static String reverse (String words) {
   Scanner sc = new Scanner(words);
   String backwards = "";

   if (sc.hasNext()) {
     String currentWord = sc.next();
     reverse(sc.nextLine());
     backwards = backwards + " " + currentWord;
   } //end if
   else {
     backwards = words;
   } //end else

   return backwards;
 }

我知道存在一些类似的问题,但他们的回答似乎并没有帮助我理解我的错误。

谢谢!

你不应该调用nextLine()因为你的输入都在一行上。 如果你从创建一个简单的辅助方法开始,你的逻辑就会清晰得多,它应该包含一个words数组和一个位置; 从那里你可以递归地构建你想要的输出,比如

private static String reverse(String[] words, int p) {
    if (p + 1 < words.length) {
        return reverse(words, p + 1) + " " + words[p];
    } else if (p < words.length) {
        return words[p];
    }
    return "";
}

那么你的public方法很容易实现,只需在空白处split原始输入并从0开始调用reverse (记住return结果)。 喜欢,

public static String reverse(String words) {
    return reverse(words.split("\\s+"), 0);
}

然后,我测试了一下

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

哪些输出(根据要求)

friend my Hello

或者,您可以让那个帮手拿走您的Scanner就像

private static String reverse(Scanner sc) {
    if (sc.hasNext()) {
        String currentWord = sc.next();
        if (sc.hasNext()) {
            return reverse(sc) + " " + currentWord;
        }
        return currentWord;
    }
    return "";
}

然后你的公共方法是

public static String reverse(String words) {
    return reverse(new Scanner(words));
}

您可以使用String.split的重载来分割第一个空格周围的words ,而不是使用Scanner

public static String reverse(String words) {
    String[] wordArr = words.split(" ", 2); // split into a maximum of 2 Strings

    if (wordArr.length > 1) { // If there is more than 1 word
        // return the first word (wordArr[0]),
        // behind the reverse of the rest of the String (wordArr[1])
        return reverse(wordArr[1]) + " " + wordArr[0];
    }

    return wordArr[0]; // else, just return the one word
}

如评论中所述,您可以使用StringBuilder而不是 Scanner 类。

此示例发送相同的单词,每次进入该方法时将它们按空格分隔,并发送要在下一次迭代中添加的单词的索引。

例如:

public class RecursiveReverse {

    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        String stringToReverse = "Hello my friend!";
        System.out.println(reverse(stringToReverse, stringToReverse.split(" ").length - 1));
    }

    public static String reverse(String words, int i) {
        if (i >= 0) { //If the index of the words is greater or equals the first word
            sb.append(words.split(" ")[i]); //We split it and append it to our StringBuilder
            sb.append(" "); //We append a space
            reverse(words, --i); //We do this again
        }
        return sb.toString(); //When the above condition doesn't match we return the StringBuilder object as a String (which contains the words reversed)
    }
}

产生这个输出:

friend! my Hello 

更好的方法是将 String 数组作为参数传递,这样您只需将字符串拆分一次(将单词作为数组发送到方法时)。

public class RecursiveReverse {

    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        String stringToReverse = "Hello my friend!";
        String words[] = stringToReverse.split(" ");
        System.out.println(reverse(words, words.length - 1));
    }

    public static String reverse(String words[], int i) {
        if (i >= 0) {
            sb.append(words[i]);
            sb.append(" ");
            reverse(words, --i);
        }
        return sb.toString();
    }
}

你扔掉递归结果:

 reverse(sc.nextLine());
 backwards = backwards + " " + currentWord;

相反,使用这个:

 backwards = reverse(sc.nextLine());
 backwards = backwards + " " + currentWord;

更好的是:

 backwards = reverse(sc.nextLine()) + " " + currentWord;
public static String reverseSentence(String sentence) {

    StringBuilder sb = new StringBuilder();

    int firstSpace = sentence.indexOf(' ');
    if (firstSpace == -1) {
        return sb.append(sentence.strip()).append(" ").toString();
    }
    String secondPart = sentence.substring(firstSpace + 1); 
    String firstPart = sentence.substring(0, firstSpace);//similar to merger sort 
    return sb.append(reverseSentence(secondPart)).append(reverseSentence(firstPart)).toString();
}

你必须使用递归吗? 没有它你也能做到。

public static String reverse(String words) {
    String[] list = words.split(" ");
    Collections.reverse(list);
    String reversed = String.join(" ", list);
    return reversed;
}

您必须在累加器中保持调用之间提取的单词。 这是一个例子。

public static String reverse(String words, String acc){
    Scanner sc = new Scanner(words);

    if(!sc.hasNext()){
        return acc;
    }

    return reverse(sc.nextLine(), acc) + " " + sc.next();
}

你会这样称呼它。

reverse("Hello my friend", "");

这不是世界上最有效的实施,但是是的...它必须有效!

如果您想要更有效的方法,请使用StringBuilder作为累加器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM