mortenoh
mortenoh

Reputation: 255

Splitting recursive groups

I have a string in this format: a,b,c[a,b,c[a]],d

And what (in the end) I want to end up with, is

a
b
c.a
c.b
c.c.a
d

Any suggestion on how to approach this task?

Upvotes: 1

Views: 67

Answers (1)

falsetru
falsetru

Reputation: 368954

Here's a possible solution using stack. (Implemented Avlin Bunk's comment.)

public static Iterable<String> split(String s) {
    List<String> result = new LinkedList<String>();
    Stack<String> stack = new Stack<String>();
    Pattern pattern = Pattern.compile("[,\\[\\]]|.+?");
    Matcher matcher = pattern.matcher(s);

    stack.push("");
    while (matcher.find()) {
        String token = matcher.group();
        if (token.equals("[")) {
            stack.push("");
        } else if (token.equals("]")) {
            if (! stack.peek().isEmpty())
                result.add(join(".", stack));
            stack.pop();
            stack.pop();
            stack.push("");
        } else if (token.equals(",")) {
            if (! stack.peek().isEmpty())
                result.add(join(".", stack));
        } else {
            stack.pop();
            stack.push(token);
        }
    }
    if (! (stack.isEmpty() || stack.peek().isEmpty()))
        result.add(join(".", stack));
    return result;
}

public static String join(String sep, Iterable<String> it) {
    // Return it[0] + sep + it[1] + sep + .... + it[lastIndex]
    String joined = "";
    boolean first = true;

    for (String s : it) {
        if (first)
            first = false;
        else
            joined += sep;
        joined += s;
    }
    return joined;
}

Example Usage:

String text = "a,b,c[a,b,c[a]],d";
for (String s : split(text))
    System.out.println(s);

See Demo run.

(Same solution in Python, Recursive solution in Python)

Upvotes: 1

Related Questions