如何从 java 中的 n 个字符的字符串中获取 x 个字符的所有可能序列

How to get all the possible sequences of x characters from a string of n characters in java

我正在玩 Java,我的问题如下:

我有一串n个字符,例如abcd,我怎样才能得到这个字符串中所有可能的 x 字符序列? "sequences" 我的意思是我只对那些尊重原始字符串中字符顺序的组合感兴趣。

例如,如果我在字符串 abcd 中寻找 2 个字符序列,我只想获得

ab、ac、ad、bc、bd、cd。

我对所有其他可能的组合(如 da、cb 等)不感兴趣,因为它们不尊重原始字符串中字符的顺序。

有什么建议吗?

这个问题可以用两个循环解决。你到目前为止做了什么来自己解决它?

    public static void print(String str) {
        for (int i = 0; i < str.length(); i++) {
           char curChar = str.charAt(i);
           for (int j = i + 1; j < str.length(); j++) {
                char otherChar = str.charAt(j);
                System.out.println(new String(new char[] { curChar, otherChar }));
            }
        }
    }

这是一个 combination without repetition 问题。 Internet 上有很多实现,您可以在 this class.

中找到一个

看看这个:

TreeSet<String> set = new TreeSet<String>();
final String placeHolder = "ignore me 'cause toElement parameter of subSet() is exclusive";
    set.add("a");
    set.add("b");
    set.add("c");
    set.add("d");
    set.add(placeHolder);
    for (String ch : set) {
        Set<String> subSet = set.subSet(ch, placeHolder);
        if (subSet.size() > 1) {
            for (String subCh : subSet) {
                if (!ch.equals(subCh)) {
                    System.out.println(ch + subCh);
                }
            }
        }
    }