繁体   English   中英

如何从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 个字符序列? 对于“序列”,我的意思是我只对那些尊重原始字符串中字符顺序的组合感兴趣。

因此,例如,如果我在字符串 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 }));
            }
        }
    }

看看这个:

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);
                }
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM