简体   繁体   中英

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:

I have a string of n characters, eg abcd, how can i get all the possible sequences of x characters in this string? 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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