You are viewing a single comment's thread. Return to all comments →
Java O(n)
public static String isBalanced(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '{' || c == '[') { stack.push(c); } else { if (stack.isEmpty()) { return "NO"; } char top = stack.pop(); if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) { 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 O(n)