打印String的所有变体的最有效方法?

时间:2014-09-24 08:38:26

标签: java arrays string

如果我有一个7字的字符串(I like it when it rains hard),我想要打印它的每个变体

  • a)大于两个字

  • b)不更改原始单词顺序。

如何做到最好?我将打印在我的最终目标之下:

 I like it when it rains hard 
 I like it when it rains 
 I like it when it 
 I like it when 
 I like it 
 I like 
 like it when it rains hard 
 like it when it rains 
 like it when it 
 like it when 
 like it 
 it when it rains hard 
 it when it rains 
 it when it 
 it when 
 when it rains hard 
 when it rains 
 when it 
 it rains hard 
 it rains 
 rains hard 

我的计划几乎实现了这一目标,但并不完全,我想知道是否有比我更聪明的解决方法......?

//Strings.java
//Goal: to print out each possible version of data without changing the original   
//order and without printing strings of less than 2 words.

public class Strings  {

  public static void main (String[] args)  {

  String var = " ";
  String data = "I like it when it rains hard";

  String [] s = data.split(" ");

  for (int i = 0 ; i <= s.length-1 ; i++)  {  //inner

    for (int j = s.length-1 ; j >= 1 ; j--)  {  //outer

      for ( int num = i ; num <= j ; num++)  {  

          var += s[num] + " ";        
      }
       System.out.println(var);
       var = " ";
    }     
  }


  }
}

4 个答案:

答案 0 :(得分:0)

如果句子中的单词数为 n ,请从 2 n 下面的 3 中收集所有数字位数(logcount)至少为2。

对于每个这样的数字,被视为一个位字段,收集该位置的位为1的单词为新句子。

答案 1 :(得分:0)

你可以像这样修改外线 for (int j = s.length - 1; j > i; j--) { //outer

您是否也希望失序?喜欢 &#34;我喜欢它&#34; - &GT; &#34;我喜欢&#34; ?

答案 2 :(得分:0)

只需更改一件事,在第二个循环 j 应该转到(i + 1)表示 j&gt; =( I + 1)

 public class Strings  {

  public static void main (String[] args)  {

  String var = " ";
  String data = "I like it when it rains hard";

  String [] s = data.split(" ");

  for (int i = 0 ; i <= s.length-1 ; i++)  {  //inner

    for (int j = s.length-1 ; j >= i+1 ; j--)  {  //outer

      for ( int num = i ; num <= j ; num++)  {  

          var += s[num] + " ";        
      }
       System.out.println(var);
       var = " ";
    }     
  }


  }
}

您可以获得相同的输出

 I like it when it rains hard 
 I like it when it rains 
 I like it when it 
 I like it when 
 I like it 
 I like 
 like it when it rains hard 
 like it when it rains 
 like it when it 
 like it when 
 like it 
 it when it rains hard 
 it when it rains 
 it when it 
 it when 
 when it rains hard 
 when it rains 
 when it 
 it rains hard 
 it rains 
 rains hard 

答案 3 :(得分:0)

它打印模式,但我怀疑它的复杂性。

    String line = "I like it when it rains hard";
    String[] tokens = line.split(" ");
    for (int i = 0; i < tokens.length; i++) {
        int len = tokens.length;
        for (int j = i + 1; j < len; len--) {
            System.out.print(tokens[i] + " ");
            for (int k = j; k < len; k++) {
                System.out.print(tokens[k] + " ");
            }
            System.out.println();
        }
    }