0

我在让这段代码在用逗号分隔的字符串上生成许多排列(排序)时遇到了一些困难......我可以只做一个普通的字符串,让排列只对字母起作用,但做起来有点困难它用逗号分隔的单词...

为了让程序识别逗号,我使用了 StringTokenizer 方法,并将其放入 arrayList 中,但这实际上是我所得到的......问题再次是我在排列每个单词时遇到了麻烦......举个例子,我将在下面发布它,然后在下面发布我的代码……谢谢大家的帮助!...通过排列,我的意思是用逗号分隔的单词的顺序

例如,如果 BufferedReader 上的输入看起来像:

red,yellow

one,two,three

PrintWriter 上的输出应如下所示:

red,yellow

yellow,red



one,two,three

one,three,two

two,one,three

two,three,one

three,one,two

three,two,one

请注意,输入总共有 3 行,包括“一、二、三”之后的空白行,而输出总共有 11 行,包括“黄色、红色”之后的一个空白行和“三、二、一”之后的两个空白行”。获得完全正确的格式至关重要,因为测试将是自动化的并且需要这种格式。另请注意,每个问题的输出行的顺序并不重要。这意味着输出的前两行也可能是:

yellow,red

red,yellow

这是我到目前为止的代码......我已经评论了一些东西所以不要担心那些部分

import java.io.*;

import java.util.*;

public class Solution

{

 public static void run(BufferedReader in, PrintWriter out)

    throws IOException

{

 String str = new String(in.readLine());

 while(!str.equalsIgnoreCase(""))
 {
 PermutationGenerator generator = new PermutationGenerator(str);
 ArrayList<String> permutations = generator.getPermutations();
 for(String str: permutations)
 {
  out.println(in.readLine());
 }
 out.println();
 out.println();

 }
 out.flush();

}







public class PermutationGenerator
{

 private String word;


public PermutationGenerator(String aWord)
{
 word = aWord;
}



public ArrayList<String> getPermutations()
{
 ArrayList<String> permutations = new ArrayList<String>();
 //if(word.length() == 0)
 //{
  //permutations.add(word);
  //return permutations;

 //}

  StringTokenizer tokenizer = new StringTokenizer(word,",");

     while (tokenizer.hasMoreTokens())
     {
      permutations.add(word);
      tokenizer.nextToken();
     }
 /*     
 for(int i = 0; i < word.length(); i++)
 {
  //String shorterWord = word.substring(0,i) + word.substring(i + 1);
  PermutationGenerator shorterPermutationGenerator = new PermutationGenerator(word);
  ArrayList<String> shorterWordPermutations =     
    shorterPermutationGenerator.getPermutations();

  for(String s: shorterWordPermutations)
  {
   permutations.add(word.readLine(i)+ s);
  }
 }*/
 //return permutations;


 }
}

}
4

2 回答 2

1
  1. Parse your input line (which is a comma-separated String ow words) into array of Strings (String[] words).
  2. Use some permutation generator that works on a array, you can easily find such generator using google. U want a generator that can be initialized with Object[], and has a method like Object[] nextPermutation().
  3. Put it together into your solution.

PS U can also use a Integer permutation generator and generate all permutations from 0 to (words.length - 1); each such permutation will give you an array of indexes of words[] to be printed out.

于 2010-01-18T09:17:32.357 回答
1

您可以使用 String.split() ( http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String) ) 来获取个人单词作为数组。您可以单独生成整数 {1..N} 的所有排列,其中 N 是单词数组的大小。然后只需使用数字排列作为索引来遍历单词数组。

于 2010-01-18T09:09:32.143 回答