1

Java でフォワード トラバーサルを使用して可能なトークンを生成したいと考えています。たとえば、「これは私の車です」という文字列があるとします。トークンを生成する必要がある

  • 「これは私の車です」
  • "これは私の"
  • "これは"
  • "これ"
  • 「私の車です」
  • 「私のです」
  • "は"
  • "私の車"
  • "私の"
  • "車"

これを行う最善の方法は何ですか?例はありますか?ありがとう。

4

4 に答える 4

5

分割されたループとネストされたループを使用した別のソリューションを次に示します。

public static void main(String[] args) {
    String original = "this is my car";

    String[] singleWords = original.split(" ");  // split the String to get the single words
    ArrayList<String> results = new ArrayList<String>();  // a container for all the possible sentences
    for (int startWord = 0; startWord < singleWords.length; startWord++) {  // starWords start with 0 and increment just until they reach the last word
        for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word 
            String next = "";
            for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
                next += singleWords[i] + " "; 
            }
            results.add(next);  // add the next result to your result list
        }
    }

    // this is just to check the results. All your sentences are now stored in the ArrayList results
    for (String string : results) {
        System.out.println("" + string);
    }
}

メソッドをテストしたときの結果は次のとおりです。

this is my car 
this is my 
this is 
this 
is my car 
is my 
is 
my car 
my 
car 
于 2012-12-11T15:13:25.423 に答える
1
import java.util.Arrays;

public class Test {

    public static void main(String[] args) {

        String var = "This is my car";
        permute(var);

    }

    public static void permute(String var) {

        if(var.isEmpty())
            return;

        String[] arr = var.split(" ");  

        while(arr.length > 0) {
            for(String str : arr) {
                System.out.print(str + " ");
            }
            arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
            System.out.println();               
        }       

        String[] original = var.split(" ");
        permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));

    }

    public static String implodeArray(String[] inputArray, String glueString) {

        String output = "";

        if (inputArray.length > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append(inputArray[0]);

            for (int i=1; i<inputArray.length; i++) {
                sb.append(glueString);
                sb.append(inputArray[i]);
            }

            output = sb.toString();

        }

        return output;

    }        

}

この本を読めば、再帰の達人になります: http://mitpress.mit.edu/sicp/

于 2012-12-11T15:17:47.257 に答える