1

I am looking to come up with the following pattern of string subsequences:

# input - ALEX
# 1 - A, L, E, X
# 2 - AL, AE, AX, LE, LX, EX
# 3 - ALE, ALX, AEX, LEX
# 4 - ALEX

I wrote this, it comes up with most, but I am missing "LX","AE","ALX" and "AEX". Can I get those without adding a third loop?

public class StringPermutations {
    public void stringPermutations(String input) {
        for(int i = 0; i<input.length();i++){
            for(int j = i; j<input.length(); j++){
                String s = input.substring(i,j+1);
                System.out.println(s);
            }
        }
    }

    public static void main(String[] args) {
        new StringPermutations().stringPermutations("ALEX");
    }
}
1
  • ...sorry for the confusion, the pattern I am seeking is commented at the top. Commented Dec 4, 2014 at 21:37

1 Answer 1

4

What you're describing is more a problem of finding all subsequences. You can't really do that by two nested for loops. It's easier to solve recursively as follows:

// Find all subsets
public List<String> helper(String input) {
    if (input.isEmpty())
        return Collections.singletonList("");

    List<String> result = new ArrayList<>();
    List<String> subResult = helper(input.substring(1));
    result.addAll(subResult);
    for (String s : subResult)
        result.add(input.charAt(0) + s);
    return result;
}

// Print all subsets using the helper method
public void stringPermutations(String input) {
    for (String s : helper(input))
        System.out.println(s);
}

This solution also includes the empty string. (Not sure why you suppressed the 0 case when describing the pattern at the top of your question ;)

With some lambda foo, you can print out the result as follows:

helper(input).stream()
             .collect(groupingBy(String::length, toList()))
             .entrySet()
             .stream()
             .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));

Output:

0: []
1: [X, E, L, A]
2: [EX, LX, LE, AX, AE, AL]
3: [LEX, AEX, ALX, ALE]
4: [ALEX]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.