parentheses - Java - Efficient parenthesis matching method to group input -
edit: should have mentioned program required strictly non recursive.
i'm trying make method assign groups matched parenthesis. example input: m (a (b c) (d (e (f g h) i) j) k) n
output be:
inputted text: m (a (b c) (d (e (f g h) i) j) k) n group 0 = m (a (b c) (d (e (f g h) i) j) k) n group 1 = (a (b c) (d (e (f g h) i) j) k) group 2 = (b c) group 3 = (d (e (f g h) i) j) group 4 = (e (f g h) i) group 5 = (f g h)
i created following method, can see, matches first encountered left parenthesis first encountered right instead of each left parenthesis signifying start of new group. can't thing of simple way replicate above output without starting over. ideas?
public class matching { public static string[] group(string s){ stack<integer> indexstack = new stack<integer>(); string[] grouparray = new string[15]; int count = 0; for(int = 0; != s.length(); i++){ /* * if character in index position left parenthesis, push current * index onto stack. if right parenthesis encountered, pop stack , * store index temporarily. use index , current position @ right * parenthesis create substring. */ if(s.charat(i) == '(') indexstack.push(i); else if( s.charat(i) == ')' ){ try{ int index = indexstack.pop(); grouparray[count++] = s.substring(index, + 1); } catch(exception e){ //an exception results popping empty stack system.out.println("unbalanced in input " + s + " @ index " + + "\n"); return null; //return null caller } } } //if stack not empty @ end of loop, return null caller if(!indexstack.isempty()){ system.out.println("unbalanced in input " + s + " @ index " + indexstack.pop() + "\n"); return null; } //initial input starts character other ( needed added. if (s.charat(0) != '(') grouparray[count++] = s; return grouparray; } }
no need use recursion. if order of output elements not restricted, try use (note there 1 iteration through chars in input):
private list<string> findsubsets(final string expresion) { final list<string> result = new arraylist<>(); final stack<stringbuilder> stack = new stack<>(); stringbuilder builder = new stringbuilder(); (char c : expresion.tochararray()) { if (c == '(') { stack.push(builder); builder = new stringbuilder(); } builder.append(c); if (c == ')') { final string value = builder.tostring(); final stringbuilder parent = stack.pop(); parent.append(value); result.add(value); builder = parent; } } if (!expresion.startswith("(")) { result.add(builder.tostring()); } return result; }
output
group 0 = (b c) group 1 = (f g h) group 2 = (e (f g h) i) group 3 = (d (e (f g h) i) j) group 4 = (a (b c) (d (e (f g h) i) j) k) group 5 = m (a (b c) (d (e (f g h) i) j) k) n
p.s. algorithm assumes, input formatted- uneven count of (
, )
might cause emptystackexception
.
Comments
Post a Comment