You are viewing a single comment's thread. Return to all comments →
//Java public static String isBalanced(String s) { if (s.length() % 2 != 0) { return "NO"; }
Stack<Character> stack = new Stack<>(); for (char ch : s.toCharArray()) { if (ch == '{' || ch == '[' || ch == '(') { stack.push(ch); } else { if (stack.isEmpty()) { return "NO"; } char top = stack.peek(); if ((ch == '}' && top == '{') || (ch == ']' && top == '[') || (ch == ')' && top == '(')) { stack.pop(); } else { return "NO"; } } } return stack.isEmpty() ? "YES" : "NO"; }
}
Seems like cookies are disabled on this browser, please enable them to open this website
Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
//Java public static String isBalanced(String s) { if (s.length() % 2 != 0) { return "NO"; }
}