2014-02-20 86 views
0

首先,我想道歉,因爲我的英文不好。現在,我如何使用遞歸返回一組字符串?我知道邏輯,但我無法弄清楚如何在從字符串中添加所有這些單詞之後返回集合。在java中返回一組字符串

例如用這樣

String s = "how do i return this?"; 

一個字符串傳遞這個串入方法後,我需要創建一個集合,然後使用遞歸以除去該字符串(將被添加到該組,並且返回該集)。

當返回集合時,我應該輸出集合到一個文件。

我的邏輯是:

//because every word in the string ends with a space 
//So I need to get the index of that space 
int n = s.indexOf(' '); 
//add each word to the set (each word start at index 0 to the index of the space ' '. 
set.add(s.substring(0, n)); 
//recursive case (keep doing this until the length of string is 0.) 
methodName(n+1, s.length()); 

我知道我可以用類變量(套)做到這一點,但我需要在這種情況下,使用本地,它似乎並沒有工作。

+0

但在這種情況下我只能用的charAt,長度,的indexOf,substring..no其它方法允許的,也沒有循環。 – JavaWannabee

+0

好!我讓你舉一個例子,不用分割遞歸調用 – nachokk

+0

謝謝你的努力。但我解決了問題。我準備好了所有的代碼,只是我沒有使用addAll來進行遞歸。 (我用add,它給了我一堆錯誤)。 – JavaWannabee

回答

0

要從方法返回任何東西,你這樣定義你的方法:

<return type> methodName(parameters) { 
    // code 
    return retval; 
} 

然後,你可以這樣調用:

<return type> retval = methodName(parameters); 

所以,定義方法返回Set<String>,並更換最後一行與此:

set.addAll(methodName(n+1, s.length())); 

最後,添加一條return語句:

return set; 

你完成了。

+0

真棒。難怪爲什麼它不工作..我用set.add(methodName(n + 1,s.length()));基本上我知道其他的一切,只是我沒有使用addAll,謝謝指出它。 – JavaWannabee

0

添加設置方法的參數:

methodName(n+1, s.length(), set); 
0

你在正確的軌道上。

我的建議

  • 使用LinkedHashSet爲您設定的實現,所以你會得到他們被插入的順序令牌
  • 您的遞歸方法必須通過設爲參數(因此它可以積累您的令牌)
  • 不要忘記添加一個方法來阻止你的遞歸方法(例如,如果你的指數字符串結束之後進入)

我的方式裏面的遞歸解決這個問題的方法有:

private static void recursiveMethod(String x, Set<String> s) 

其中x是前一個字符串的子字符串。

0

你需要一個基本案例來知道你在哪裏完成遞歸,實際上使用indexOf是一個很好的選擇,如果它是-1,那麼你就沒有任何事情要做。

實施例:

import java.util.HashSet; 
import java.util.Set; 

public class RecursionExample { 

    public static void main(String[] args) { 
     Set<String> set = new HashSet<>(); 
     methodName("how do i return this?", set); 
     System.out.println(set); 
    } 

    static void methodName(String s, Set<String> set) { 
    // because every word in the string ends with a space 
    // So I need to get the index of that space 
    int n = s.indexOf(' '); 
    // base case 
    if (n < 0) { 
     set.add(s); 
     return; 
    } 
    // add each word to the set (each word start at index 0 to the index of 
    // the space ' '. 
    set.add(s.substring(0, n)); 
    // recursive case (keep doing this until the length of string is 0.) 
    methodName(s.substring(n + 1, s.length()), set); 
} 
} 

OUTPUT:

[how, return, do, this?, i]