Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #369 Parse matching brackets

Generate a collection, a, of index-values, given the text, s, containing paired bracket values.

For example, "{ { } } { }" is `(0, 6) (2, 4) (8, 10)`.

https://en.wikipedia.org/wiki/Bracket_(mathematics)
https://en.wikipedia.org/wiki/Scope_(computer_science)

import java.util.ArrayList;
import java.util.List;
List<int[]> a = new ArrayList<>();
int i, x, y, n = s.length(), c;
for (i = y = 0; i < n; ++i)
    if (s.charAt(i) == '{') {
        x = i + ++y;
        while (x < n) {
            c = s.charAt(x++);
            if (c == '{') ++y;
            else if (c == '}')
                if (--y == 0) break;
        }
        a.add(new int[] { i, x - 1 });
    }

New implementation...
< >
reilas