Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中给定长度的不同字母字符串与给定字符串_Java_String_Distinct_Builder - Fatal编程技术网

java中给定长度的不同字母字符串与给定字符串

java中给定长度的不同字母字符串与给定字符串,java,string,distinct,builder,Java,String,Distinct,Builder,所以,我最近学习了如何生成给定字符串中给定长度的每个可能的子字符串。现在,我试图找到给定长度的所有可能的不同字符串。我的意思是,字符串有所有不同的字母。秩序不重要。到目前为止,我得到的是: public static void distinctStrings(int maxLength, char [] alphabet, String news){ //converts char array to a string builder so you can mutate it St

所以,我最近学习了如何生成给定字符串中给定长度的每个可能的子字符串。现在,我试图找到给定长度的所有可能的不同字符串。我的意思是,字符串有所有不同的字母。秩序不重要。到目前为止,我得到的是:

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,就是这样。我用distinctStrings2,{'A','B','C'}运行它。我也会很感激在如何优化它的指针。我想编写代码的一般想法是,如果我插入distinctStrings2,{'A','B','C',,它应该输出AB,AC,BC。秩序不重要。另一方面,如果我想输出所有可能的字符串,它将包括像AA、BB和CC这样的字符串,而我不想要这些字符串。术语distinct strings表示一个字符串,其中包含的字符都是不同的。
我之所以使用字符串新闻(一开始是空白的),是因为它是一个起点,所以我可以自己运行这个方法,它在新的字符串新闻上运行这个方法。

这就是你想要的吗

公共静态void distinctStringsint maxLength、字符[]字母、字符串新闻{ //只执行不同单词的集合 Set wordsDistinct=新哈希集; //查找长度为maxLength的所有不同单词 对于int i=0;i DistinctStrings ds=新DistinctStrings; 字符a[]={'',';'}; D.distinctStrings4,a,lorem ipsum dolor sit amet;乱数假文; 输出:

psum
dolo
olor
amet
ipsu
orem
lore

把它们都放在一个哈希集中。你是在问为了存储特定长度的唯一字符串,最佳循环是什么?不,代码不起作用。它输出AB,然后就是了。我在寻求一种方法来修复它,或许可以优化它。现在效率非常低。我将查找什么是hashset字符串。谢谢你的提示。这就是你要找的吗?不,我想你不太明白。我打算为我的代码,例如给定一个字符串,打印所有可能的不同字符子字符串。我将编辑这个问题,以使它更清楚,给定一个字符数组,对不起。在您的例子中,char数组只是一个,因此输出应该是:lorem ipsum dolor sit amet;lorem ipsum在末尾加一个空格,再加一个分号,然后加一个空格再加一个分号,因为它只取初始字符串,并添加所有可能的字符串,这些字符串具有从字符数组中提取的不同字符,在您的情况下,字符数组就是空格和分号。