Q.請寫一段代碼來計算給定文本內字元“A”的個數。分別用迭代和遞迴兩種方式。
A.假設給定文本為”AAA rating”。迭代方式就很直觀,如下:
View Code
1 public class Iteration { 2 3 public int countA(String input) { 4 if (input == null || input.length( ) == 0) { 5 return 0; 6 } 7 8 int count = 0; 9 for (int i = 0; i < input.length( ); i++) {10 if(input.substring(i, i+1).equals("A")){11 count++;12 }13 }14 return count;15 }16 17 public static void main(String[ ] args) {18 System.out.println(new Iteration( ).countA("AAA rating")); // Ans.319 }20 }
接下來,遞迴方式的代碼如下:
View Code
1 public class RecursiveCall { 2 3 public int countA(String input) { 4 5 // exit condition – recursive calls must have an exit condition 6 if (input == null || input.length( ) == 0) { 7 return 0; 8 } 9 10 int count = 0;11 12 //check first character of the input13 if (input.substring(0, 1).equals("A")) {14 count = 1;15 }16 17 //recursive call to evaluate rest of the input18 //(i.e. 2nd character onwards)19 return count + countA(input.substring(1));20 }21 22 public static void main(String[ ] args) {23 System.out.println(new RecursiveCall( ).countA("AAA rating")); // Ans. 324 }25 }
遞迴比較難以理解,我們用下面的圖來進行說明。
Q.理解遞迴需要瞭解哪些概念?
A. 可重新進入方法(re-entrant method)是可以安全進入的方法,即使同一個方法正在被執行,深入到同一個線程的調用棧裡面也不會影響此次執行的安全性。一個非可重新進入方法則不是可以安全進入的。例如,加入寫檔案或者向檔案中寫入日誌的方法不是可重新進入方法時,有可能會毀壞那個檔案。
如果一個方法調用了其自身的話,我們稱之為遞迴調用。假定棧空間足夠的話,儘管遞迴調用比較難以調試,在Java語言中實現遞迴調用也是完全可行的。遞迴方法是眾多演算法中替代迴圈的一個不錯選擇。所有的遞迴方法都是可重新進入的,但是不是所有可重新進入的方法都是遞迴的。
棧遵守LIFO(Last In First Out)規則,因此遞迴調用方法能夠記住“調用者”並且知道此輪執行結束之返回至當初的被調用位置。遞迴利用系統棧來儲存方法調用的返回地址。 Java是一種基於棧設計的程式設計語言。
順著這個思路還有那些問題可以用來面試?
Q.什麼情況下應該採用遞迴?
A. 上面的例子中其實不必採用遞迴,迴圈的方式可以達到目的,但是在某些情況下採用遞迴方式則代碼會更加簡短易讀。遞迴方法在迴圈樹結構以及避免醜陋的嵌套迴圈的情況下是非常好用的。
Q.什麼是尾遞迴,為什麼需要尾遞迴?上面的代碼用尾遞迴方式如何重寫?
A. 常規遞迴方法(亦稱,頭遞迴)在上面示範了,這種方式會增加調用棧的大小。每次遞迴,其入口需要被記錄在棧中。方法返回之前需要給countA(input.substring(1)的結果加一個count。假定count大於1,那麼返回結果就是count + countA(input.substring(1)),當然事先要算出來countA(input.substring(1))才行。同時,這也意味著直到countA(input.substring(1)計算出來才能得到最終的結果。因此,最後需要做的事其實是加法運算,而非遞迴本身。
尾遞迴的好處是什嗎?
在尾遞迴中,最後要做的是遞迴,加法運算在之前就已經完成了。一輪遞迴調用完畢後就沒有其他事情了(除了加法運算),因此調用時產生的資訊也就沒什麼用了。這些無用資訊可以丟棄,然後用一組新的參數來調用一次遞迴方法來產生一個新的結果。這也就是說,棧調用減少帶來了記憶體消耗減少並且程式的效能更好。
尾遞迴重寫的代碼如下:
View Code
1 public class TailRecursiveCall { 2 3 public int countA(String input) { 4 5 // exit condition – recursive calls must have an exit condition 6 if (input == null || input.length() == 0) { 7 return 0; 8 } 9 10 return countA(input, 0) ;11 }12 13 public int countA(String input, int count) {14 if (input.length() == 0) {15 return count;16 }17 18 // check first character of the input19 if (input.substring(0, 1).equals("A")) {20 count = count + 1;21 }22 23 // recursive call is the last call as the count is cumulative24 return countA(input.substring(1), count);25 }26 27 public static void main(String[] args) {28 System.out.println(new TailRecursiveCall().countA("AAA rating"));29 }30 }