[英]Recursive implementation of indexOf
我已經在這里和其他地方閱讀了許多以前的問題,但我還沒有找到我需要的東西。 我需要編寫 indexOf 的遞歸實現。 問題是我不能使用任何局部變量,並且必須只提供一個字符串和一個字符作為輸入。
該方法應該返回一個介於 0 和字符串長度之間的值 - 如果找到了 char,則返回 1,如果不存在,則返回 -1。 我知道實際的“indexOf”也允許您搜索字符串,但這種方法被簡化了。
我試過這個,但它很愚蠢,因為我使用了真正的indexOf :
public static int indexOf(String s, char c){
if(s.indexOf(c) < 0){ // I'd like to change this
return -1;
}
if (s.length() == 0) //base case #1
{
return -1;
}
else if (s.charAt(0) == c) //base case #2
{
return 0;
}
else {
return 1 + indexOf(s.substring(1), c);
}
}
我特別看到了這一點,但是可以在沒有變量的情況下編寫它嗎? 謝謝
如果您不想要局部變量,則需要在內部方法中進行遞歸。
優點是速度要快得多,因為它不必創建新的String
對象,並且邏輯是尾遞歸的,如果與優化它的語言一起使用的話。
public static int indexOf(String s, char c) {
return indexOf0(s, c, 0);
}
private static int indexOf0(String s, char c, int index) {
if (index == s.length())
return -1;
if (s.charAt(index) == c)
return index;
return indexOf0(s, c, index + 1);
}
您鏈接的答案似乎是一個很好的答案...我建議只需將其中使用的變量實例替換為調用變量存儲的方法即可。
下面我簡單的編輯一下代碼:
public static int indexOf(char ch, String str) {
// Returns the index of the of the character ch
if (str == null || str.equals("")) {
// base case: no more string to search; return -1
return -1;
} else if (ch == str.charAt(0)) {
// base case: ch is at the beginning of str; return 0
return 0;
}
return indexOf(ch, str.substring(1)) == -1 ? -1 : 1 + indexOf(ch, str.substring(1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.