stack - Java balanced expressions check {[()]} -
i trying create program takes string argument constructor. need method checks whether string balanced parenthesized expression. needs handle ( { [ ] } ) each open needs balance corresponding closing bracket. example user input [({})] balanced , }{ unbalanced. doesn't need handle letters or numbers. need use stack this.
i given pseudocode can not figure how implement in java. advice awesome.
update- sorry forgot post had far. messed because @ first trying use char , tried array.. im not sure go.
import java.util.*; public class expression { scanner in = new scanner(system.in); stack<integer> stack = new stack<integer>(); public boolean check() { system.out.println("please enter expression."); string newexp = in.next(); string[] exp = new string[newexp]; (int = 0; < size; i++) { char ch = exp.charat(i); if (ch == '(' || ch == '[' || ch == '{') stack.push(i); else if (ch == ')'|| ch == ']' || ch == '}') { //nothing match if(stack.isempty()) { return false; } else if(stack.pop() != ch) { return false; } } } if (stack.isempty()) { return true; } else { return false; } } }
i hope code can help:
import java.util.stack; public class balancedparenthensies { public static void main(string args[]) { system.out.println(balancedparenthensies("{(a,b)}")); system.out.println(balancedparenthensies("{(a},b)")); system.out.println(balancedparenthensies("{)(a,b}")); } public static boolean balancedparenthensies(string s) { stack<character> stack = new stack<character>(); for(int = 0; < s.length(); i++) { char c = s.charat(i); if(c == '[' || c == '(' || c == '{' ) { stack.push(c); } else if(c == ']') { if(stack.isempty() || stack.pop() != '[') { return false; } } else if(c == ')') { if(stack.isempty() || stack.pop() != '(') { return false; } } else if(c == '}') { if(stack.isempty() || stack.pop() != '{') { return false; } } } return stack.isempty(); } }
Comments
Post a Comment