Parsing Nested Bracket String in java -


i want parse strings (nested) brackets , values like:

a,(b,c),(d,(b,d),x) 

i want inner tuples f.ex arraylist, arraylist(b,c) or arraylist(d,arraylist(b,d)).

my first idea use stack, have problems when have tuple in tuple , after inner tuple comes value, (z,(a,b),c).

public static arraylist<object> parse(string str, arraylist<object> result) {     arraylist<object> tmp = result;     if (str.length() == 0) {         return tmp;     } else if (str.charat(0) == '(') {         arraylist<object> al = new arraylist<object>();         tmp.add(al);         str = str.substring(1, str.length());         return parse(str, tmp);     }else if(str.charat(0) == ',')     {         str = str.substring(1,str.length());         return parse(str,tmp);     }     else {         arraylist<string> al = new arraylist<string>();         al.add(""+str.charat(0));         tmp.add(al);          str = str.substring(1, str.length());         return parse(str,tmp);     } }  public static void main(string[] args) {     arraylist<object> al = new arraylist<object>();     system.out.println(parse("a,(b),(c,(d,e),f)",al));   } 

output:

[[a], [], [b], [)], [], [c], [], [d], [e], [)], [f], [)]]

what problems when use stack? should able use stack mimic recursive algorithm this. think of recursively building arraylists. @ base case return arraylist when encounter ')' or end of string, if encounter character add list , if encounter '(' should recurse. have make sure object type abstract enough apply both arraylists , objects reading in.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -