所以,我最近學會了如何生成給定字符串給定長度的每個可能的子字符串。現在,我試圖找到給定長度的每個可能的DISTINCT字符串。我的意思是,字符串有所有不同的字母。順序無關緊要。到目前爲止,我所擁有的是:從給定的字符串給定長度的字符的差異字符串
public static void distinctStrings(int maxLength, char [] alphabet, String news){
//converts char array to a string builder so you can mutate it
String a = new String (alphabet);
StringBuilder nAlphabet = new StringBuilder(a);
//if it is max
if(news.length()==maxLength) System.out.println(news);//full.add(news);
//describes the way to get the distinct string:
else{
//if alphabet.length>0 to avoid errors when the alphabet length has reached 0, probably could just do a while loop
if(alphabet.length>0){
for(int i = 0; i < alphabet.length; i++) {
String oldCurr = news;
news += nAlphabet.charAt(i);
//deletes char so it can't be used again
nAlphabet.deleteCharAt(i);
String c = nAlphabet.toString();
char[] b = c.toCharArray();
//reprocesses the strings.
distinctStrings(maxLength,b,news);
news = oldCurr;
}
}
}
編輯: 因此,代碼不工作,我不知道爲什麼。它輸出「AB AB」,就是這樣。我用distinctStrings(2,{'A','B','C'},「」)運行它。我也很欣賞如何優化它的指針。如果我插入distinctStrings(2,{'A','B','C'},「」),它應該輸出AB,AC,BC,我想要編碼的一般想法是。順序應該不重要。另一方面,如果我想要輸出所有可能的字符串,它將包括像AA,BB和CC這樣的字符串,但我不想要這些字符串。術語不同的字符串意味着一個字符串,使得包含在其中的字符全部不同。 我使用字符串「news」(在開始時只是空白)的原因是它是一個起點,所以我可以自己運行該方法,並在新字符串「news」上運行該方法。
只要把它們放在一個HashSet的''。 –
2015-02-06 02:24:07
您是否問最佳循環是爲了存儲特定長度的唯一字符串? – 2015-02-06 02:25:19
不,代碼無法正常工作。它輸出「AB AB」,就是這樣。我正在尋求解決方法並可能對其進行優化。現在它非常低效。我將查找一個hashset字符串是什麼。感謝提示。 – user4500882 2015-02-06 02:30:40