For example if the parenthesis/brackets is matching in the following:
({}) (()){}() ()
and so on but if the parenthesis/brackets is not matching it should return false, eg:
{} ({}( ){}) (()
and so on. Can you please check this code? Thanks in advance.
public static boolean isParenthesisMatch(String str) { Stack<Character> stack = new Stack<Character>(); char c; for(int i=0; i < 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)); }
If a symbol is an opening parenthesis, push it on the stack as a signal that a corresponding closing symbol needs to appear later. If, on the other hand, a symbol is a closing parenthesis, pop the stack. As long as it is possible to pop the stack to match every closing symbol, the parentheses remain balanced.
If the current character is a starting bracket ( ( or { or [ ) then push it to stack. If the current character is a closing bracket ( ) or } or ] ) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are Not Balanced.
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to 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; i < 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(); }
This code is easier to understand:
public static boolean CheckParentesis(String str) { if (str.isEmpty()) return true; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < str.length(); i++) { char current = str.charAt(i); if (current == '{' || current == '(' || current == '[') { stack.push(current); } if (current == '}' || current == ')' || current == ']') { if (stack.isEmpty()) return false; char last = stack.peek(); if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[') stack.pop(); else return false; } } return stack.isEmpty(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With