2012-06-06 24 views
4

我被要求寫一些能夠確定數組是否是另一個更大數組的子集的東西。我決定從一個更簡單的問題開始,寫出一個函數來確定字符數組中存在的字符。 我想出了這個代碼:數組中的字符的遞歸搜索(Java)

private static boolean findSequenceRecHelper(char [] findIn, char c, int index) { 
    boolean result = false; 
    if(index<findIn.length) { 
     if(findIn[index] == c) { 
      result = true; 
     } 
     else { 
      findSequenceRecHelper(findIn,c,index+1); 
     } 
    } 
    return result; 
} 

我做了一些調試,發現在整個char[]陣列和當數組中的元素等於期望值函數循環,result變成true。但後來又回到falsefalse實際上是返回,這是不正確的。

我在這裏找不到一個錯誤 - 有人可以幫我解決這個問題。

回答

4

在遞歸步驟:

else 
findSequenceRecHelper(findIn,c,index+1); 

你應該return由遞歸調用的返回值。否則 - 什麼都不做,遞歸調用實際上是多餘的。

private static boolean findSequenceRecHelper(char [] findIn, char c, int index) 
{ 
boolean result = false; 
if(index<findIn.length) 
{ 
    if(findIn[index] == c) 
     result = true; 
    else 
    return findSequenceRecHelper(findIn,c,index+1); 
    //^ 
    //added return here 
} 
return result; 
} 
0

更改此:

if(index<findIn.length) 
{ 
    if(findIn[index] == c) 
     result = true; 
    else 
     return findSequenceRecHelper(findIn,c,index+1); 
} 
0

你對遞歸調用沒有做任何事情。相反,你會想要設置它返回的結果,以便你可以遞歸地返回它,即。 result = findSequenceRecHelper(findIn,c,index+1);在您的if聲明中。

3

當你遞歸地調用你的方法時,你不會存儲它的返回值,有效地失去指示符是否被找到。你實際想要做的是將結果向上返回到當前之上的遞歸調用。

試試這個:

private static boolean findSequenceRecHelper(char [] findIn, char c, int index) 
{ 
    boolean result = false; 
    if(index<findIn.length) 
    { 
     if(findIn[index] == c) 
      return true; 
     else 
      return findSequenceRecHelper(findIn,c,index+1); 
    } 
}