Check if a string which represents a math exercise is balanced in terms of parentheses Remove spaces from a string
Anonymous
public class CheckParenthesesBalanced { public static void main(String[] args) { String s = "n({})ir"; System.out.println(isBalanced(s)); } private static boolean isBalanced(String str) { Stack stack = new Stack(); final Set openParentheses = Set.of('(', '{', '['); final Set closedParentheses = Set.of(')', '}', ']'); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (openParentheses.contains(c)) { stack.push(c); } else if (closedParentheses.contains(c)) { Character popped = stack.pop(); if (popped != getComplementBracket(c)) { return false; } } } return true; } private static char getComplementBracket(char c) { switch (c) { case ')': return '('; case '}': return '{'; case ']': return '['; default: throw new IllegalArgumentException("no bracket for char "+c); } } }
Check out your Company Bowl for anonymous work chats.