java - Parenthesis/Brackets Matching using Stack algorithm -
for example if parenthesis/brackets matching in following:
({}) (()){}() ()
and on if parenthesis/brackets not matching should return false, eg:
{} ({}( ){}) (()
and on. can please check code? in advance.
public static boolean isparenthesismatch(string str) { stack<character> stack = new stack<character>(); char c; for(int i=0; < str.length(); i++) { c = str.charat(i); if(c == '{') return false; if(c == '(') stack.push(c); if(c == '{') { stack.push(c); if(c == '}') if(stack.empty()) return false; else if(stack.peek() == '{') stack.pop(); } else if(c == ')') if(stack.empty()) return false; else if(stack.peek() == '(') stack.pop(); else return false; } return stack.empty(); } public static void main(string[] args) { string str = "({})"; system.out.println(weekly12.parenthesisothermatching(str)); }
your code has confusion in handling of '{' , '}' characters. should entirely parallel how handle '(' , ')'.
this code, modified yours, seems work properly:
public static boolean isparenthesismatch(string str) { if (str.charat(0) == '{') return false; stack<character> stack = new stack<character>(); char c; for(int i=0; < str.length(); i++) { c = str.charat(i); if(c == '(') stack.push(c); else if(c == '{') stack.push(c); else if(c == ')') if(stack.empty()) return false; else if(stack.peek() == '(') stack.pop(); else return false; else if(c == '}') if(stack.empty()) return false; else if(stack.peek() == '{') stack.pop(); else return false; } return stack.empty(); }
Comments
Post a Comment