Find the first outermost brackets

  • A+
Category:Languages

I need to find out the first outermost(not nested) brackets indexes.

For example

[]                         output: 0, 1 1[2]                       output: 1, 3 3[a2[c]]2[abc]3[cd]        output: 1, 7 

I can find it by lots of conditions, current code:

public static void main(String[] args) {     String input = "3[a2[c]]2[abc]3[cd]ef";     int first = 0;     int second = 0;      int count = 0;     boolean found = false;     for (int index = 0; index < input.length(); index++) {         if (input.charAt(index) == '[') {             count++;             if (found == false) {                 found = true;                 first = index;             }         } else if (input.charAt(index) == ']') {             count--;             if (found && count == 0) {                second = index;                break;             }         }     }      System.out.println(first);     System.out.println(second); } 

Is there more clean way to do it?


Using a Stack may be more elegant:

String input = "3[a2[c]]2[abc]3[cd]ef"; Stack<Integer> stack = new Stack<> (); int first = -1; int second = -1;  for (int index = 0; index < input.length(); index++) {     if (input.charAt(index) == '[') {         stack.push(index);     } else if (input.charAt(index) == ']' && !stack.isEmpty ()) {         first = stack.pop ();         if (stack.isEmpty ()) {             second = index;             break;         }     } }  if (first >= 0 && second >= 0) {     System.out.println(first);     System.out.println(second); } else {   System.out.println ("not found"); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: