我遇到了一些困難讓這段代碼生成一串用逗號分隔的字符串(排序)......我只能做一個常規字符串和排列只能在字母上工作,但用逗號分隔單詞時會更困難...排列(排序)的一串文字,但用逗號隔開
要讓程序識別逗號,我使用了StringTokenizer方法,它到一個arrayList,但這是真的,我已經得到...再次的問題是,我有麻煩permuting每個單詞...舉一個例子,我會張貼它下面,然後我的代碼下面。 ..感謝你的幫助每個人! ...和排列我指的是通過分離的話排序的逗號
例如,如果輸入進來的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;
}
}
}
不鼓勵使用StringTokenizer。來自StringTokenizer文檔: 「StringTokenizer是一個遺留類,爲了兼容性原因被保留,儘管在新代碼中不鼓勵使用它。建議任何尋求該功能的人都使用String或java.util.regex包的拆分方法「。 http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html – Averroes 2010-01-18 09:44:09