原文: https://www.programiz.com/java-programming/examples/reverse-sentence
public class Reverse {
public static void main(String[] args) {
String sentence = "Go work";
String reversed = reverse(sentence);
System.out.println("The reversed sentence is: " + reversed);
}
public static String reverse(String sentence)
{
if (sentence.isEmpty())
return sentence;
return reverse(sentence.substring(1)) + sentence.charAt(0);
}
}
运行该程序时,输出为:
The reversed sentence is: krow oG
在上面的程序中,我们有一个递归函数reverse()
。
在每次迭代中,我们使用charAt(0)
将下一个reverse()
函数的结果添加(连接)到句子的第一个字符。
递归调用必须在charAt()
之前,因为这样最后一个字符将开始添加到左侧。 如果您颠倒顺序,您将得到原始句子。
最后,我们以空的sentence
和reverse()
返回相反的句子结束。
执行步骤
迭代 | reverse() |
substring() |
reversedString |
---|---|---|---|
1 | reverse("Go work") |
"o Work" |
result + "G" |
2 | reverse("o Work") |
" Work" |
result + "o" + "G" |
3 | reverse(" Work") |
"Work" |
result + " " + "o" + "G" |
4 | reverse("Work") |
"ork" |
result + "W" + " " + "o" + "G" |
5 | reverse("ork") |
"rk" |
result + "o" + "W" + " " + "o" + "G" |
6 | reverse("rk") |
"k" |
result + "r" + "o" + "W" + " " + "o" + "G" |
7 | reverse("k") |
"" |
result + "k" + "r" + "o" + "W" + " " + "o" + "G" |
最后 | reverse("") |
- |
"" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG" |