简体   繁体   English

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

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

I am playing with Java and my problem is the following:我正在玩 Java,我的问题如下:

I have a string of n characters, eg abcd, how can i get all the possible sequences of x characters in this string?我有一个 n 个字符的字符串,例如 abcd,我怎样才能得到这个字符串中所有可能的 x 个字符序列? with "sequences" i mean that I am interested ONLY in those combinations that respect the order of the characters in the original string.对于“序列”,我的意思是我只对那些尊重原始字符串中字符顺序的组合感兴趣。

So for instance if I am looking for 2 characters sequences in the string abcd I would like to obtain only因此,例如,如果我在字符串 abcd 中查找 2 个字符序列,我只想获得

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

I am not interested in all the other possible combinations (such as da, cb etc), because they do not respect the order of the characters in the original string.我对所有其他可能的组合(例如 da、cb 等)不感兴趣,因为它们不尊重原始字符串中字符的顺序。

Any suggestion?有什么建议吗?

This is a combination without repetition problem.这是一个没有重复问题的组合 There are plenty of implementations around the Internet, you can find one in this class .互联网上有很多实现,你可以在这个类中找到一个。

The problem is solvable with two loops.这个问题可以用两个循环来解决。 What have you done so far to solve it on your own?到目前为止,您为自己解决了哪些问题?

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

Take a look at this:看看这个:

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