使用递归来反转字符串

时间:2017-02-28 22:58:38

标签: java string recursion reverse

我试图使用递归逐字反转String。 (例如:“Hello my friend”被反转为“friend my Hello”)这是我试图为此方法编写的代码。我尝试了多个类似的变体,但输出只是字符串的第一个或最后一个字。我认为“破碎”的部分是第一个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;
 }

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

谢谢!

7 个答案:

答案 0 :(得分:4)

您不应该致电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空白处的原始输入,并从reverse开始致电0(记住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));
}

答案 1 :(得分:3)

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

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
}

答案 2 :(得分:1)

如评论中所述,您可以使用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数组作为参数传递,这样您只能拆分一次(当将字作为数组发送到方法时)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();
    }
}

答案 3 :(得分:1)

你扔掉了递归结果:

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

相反,请使用:

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

更好的是:

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

答案 4 :(得分:1)

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();
}

答案 5 :(得分:0)

你必须使用递归吗?没有它你就可以做到。

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

答案 6 :(得分:0)

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

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作为累加器。