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

时间:2015-02-06 02:23:32

标签: java string distinct builder

所以,我最近学会了如何生成给定字符串给定长度的每个可能的子字符串。现在,我正在尝试找到给定长度的每个可能的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”上运行该方法。 / p>

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

public static void distinctStrings(int maxLength, char[] alphabet, String news) {
    // a set that will enforce only distinct words
    Set<String> wordsDistinct = new HashSet<String>();

    // find all distinct words, of length maxLength
    for (int i = 0; i < news.length() - maxLength; ++i) {
        // possible a valid word
        String word = news.substring(i, i + maxLength);

        // validation test
        boolean isValid = true;
        for (char c: alphabet) {
            if (word.contains(String.valueOf(c))) {
                isValid = false;
                break;
            }
        }
        if (!isValid)
            continue; // probably not valid, because of the alphabet, or maybe is vice-versa 

        // add the word to set. If already there ... the set will ignore it.
        wordsDistinct.add(word);
    }

    // print the strings
    for (String s : wordsDistinct) {
        System.out.println(s);
    }
}

我用:

运行它
    DistinctStrings ds = new DistinctStrings();
    char a[] = {' ', ';'};
    ds.distinctStrings(4, a, "lorem ipsum dolor sit amet; lorem ipsum");

输出:

psum
dolo
olor
amet
ipsu
orem
lore