You are viewing a single comment's thread. Return to all comments →
Using Deque and Map (Java 15):
import java.util.Deque; import java.util.LinkedList; import java.util.Map; import java.util.Scanner; class Solution { private static final Map<Character, Character> brackets = Map.of( ')', '(', '}', '{', ']', '[' ); private static boolean check(String input) { Deque<Character> stack = new LinkedList<>(); for (char c : input.toCharArray()) { if (brackets.containsKey(c)) { if (stack.isEmpty()) return false; if (brackets.get(c) != stack.removeLast()) return false; continue; } stack.add(c); } return stack.isEmpty(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { boolean isBalanced = check(sc.next()); System.out.println(isBalanced ? "true" : "false"); } sc.close(); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →
Using Deque and Map (Java 15):