2014-03-03 83 views
0

此代碼不起作用。請幫助修復它.............................................. .................................................. .................java使用遞歸查找字符串中的子串

/** 
     Recursive method for looking for a substring in a string. 
     @param text look in 
     @param target look for as substring 
     @return true if target is a substring of text 
    */ 
    public static boolean find(String text, String target) 
    { 
     //-----------Start below here. To do: approximate lines of code = 4 
     // 1. base case: null 
     if (text == null) {return false;}   
     //2. base case: target too long 
     if (target.length() > text.length()) {return false;} 
     //3. base case: same length 
     if (text.length() == target.length()) {return false;} 
     //4. base case: startsWith OR 5. recursive case 
     return true; 
    } 
+1

請仔細閱讀[如何提問](https://stackoverflow.com/questions/如何提問),然後[編輯]你的問題。 –

+0

你正在得到什麼錯誤? –

+3

我在這裏沒有看到遞歸。我認爲你的代碼不完整 – Rami

回答

2

試試這個

/** 
Recursive method for looking for a substring in a string. 
@param text look in 
@param target look for as substring 
@return true if target is a substring of text 
*/ 
public static boolean find(String text, String target) 
{ 
//-----------Start below here. To do: approximate lines of code = 4 
// 1. base case: null 
if (text == null || target == null) {return false;} // added target null check  
//2. base case: target too long 
if (target.length() > text.length()) {return false;} 
//3. base case: same length 
if (text.length() == target.length()) {return text.equals(target);} 
//4. base case: startsWith OR 5. recursive case 
return text.startsWith(target) || find(text.substring(1) , target); 
} 
+1

你真的應該在1. base情況下檢查'text'和'target'爲null,否則你可能會得到一個異常。 – jmodrak

+0

是的,但這看起來像一個家庭作業問題..所以我堅持嚴密的結構,因爲文本是在遞歸修改它的良好實踐,有適當的基本情況下它 – clancer

+0

它肯定看起來像一個家庭作業。這會讓我更加強化它,使它永遠不會讓我失望。我認爲結構基礎案例是由老師創建的,我認爲任何代碼都已經被學生插入了,而他可能認爲他只與最後一行發生衝突。 – jmodrak

相關問題