You are viewing a single comment's thread. Return to all comments →
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner sn = new Scanner(System.in); while(sn.hasNextLine()){ String str = sn.nextLine(); boolean isBalanced = isBalanced(str); System.out.println(isBalanced); } } public static boolean isBalanced(String s){ Stack<Character> stack = new Stack<>(); for(char ch: s.toCharArray()){ if(ch=='(' || ch=='{' || ch=='['){ stack.push(ch); }else if(ch==')' || ch=='}' || ch==']'){ if(stack.isEmpty()) return false; char top = stack.pop(); if( ( ch==')' && top != '(' ) || ( ch=='}' && top != '{' ) || ( ch==']' && top != '[' ) ){ return false; } } } return stack.isEmpty(); } }
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 →