所以,我最近学会了如何生成给定字符串给定长度的每个可能的子字符串。现在,我试图找到给定长度的每个可能的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