You are viewing a single comment's thread. Return to all comments →
import java.util.*; class Solution{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String str = scan.next(); System.out.println(IsBalanced(str)); } scan.close(); } public static boolean IsBalanced(String str) { Stack<Character> stack = new Stack<Character>(); for (char ch : str.toCharArray()) { if (ch == '{' || ch == '(' || ch == '[') { stack.push(ch); } else if (ch == '}' || ch == ')' || ch == ']') { if (stack.isEmpty()) { return false; // Unmatched closing parenthesis } char top = (char) stack.pop(); if (!IsMatch(top, ch)) return false; } } return stack.isEmpty(); } public static boolean IsMatch(char ch1, char ch2) { return (ch1 == '{' && ch2 == '}') || (ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'); } }
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 →