[英]Reversing a String using recursion in Java
我目前正在着手處理Java遞歸。 遇到下面的代碼,我無法弄清楚遞歸方法如何產生反向String。 任何解釋將不勝感激!
class Backwards {
String str;
Backwards(String s) {
str = s;
}
void backward(int idx) {
if(idx != str.length()-1) {
backward(idx+1);
}
System.out.print(str.charAt(idx));
}
}
class BWDemo {
public static void main(String args[]) {
Backwards s = new Backwards("This is a test");
s.backward(0);
}
}
如果使用筆和紙進行調試,則很容易看到發生了什么。
基本上-它到達字符串的末尾,並從頭到尾開始逐字符打印char。
看一下backward
方法。 它能做什么? 一步步:
因此,如果我們要擴展遞歸調用,它將是(對於字符串“ hel”):
可視化:
因此,最終的輸出是“ leh”,這就是我們想要的。
以字符串“ ABCD”為例。
backward(0)
{
backward(1)
{
backward(2)
{
backward(3)
{
print D
}
print C
}
print B
}
print A
}
嘗試這個:
private static String reverse(String str) {
if (str == null || str.length() == 0) return "";
return str.toCharArray()[str.length() - 1] + reverse(str.substring(0, str.length() - 1));
}
希望會有所幫助。
向后看一下該方法。
void backward(int idx) {
if(idx != str.length()-1) {
backward(idx+1);
}
System.out.print(str.charAt(idx));
}
它使用一個索引號並打印該索引位置中的字符。 然后它再次調用它自己(這就是遞歸的原因),但是現在索引增加1,因為您要打印下一個字符- 向后(idx + 1);
查看不同索引編號的效果:
Backwards s = new Backwards("test");
索引= 0 s.backward(0); 輸出:tset
索引= 1 s.backward(1); 輸出:tse
索引= 2 s.backward(2); 輸出:ts
你的班:
public class Backwards {
String str;
Backwards(String s) {
str = s;
}
String backward(int i) {
int j = i+1;
if(i <= str.length())
return str.charAt(str.length()-i) + backward(j);
return "";
}
}
主要:
public static void main(String[] args) {
Backwards s = new Backwards("This is a test");
System.out.println(s.backward(1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.