This is my solution to challenge “Stacks: Balanced Brackets” on HackerRank. Click here to see the challenge.
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static HashMap< Character, Character> bracketsMap = new HashMap<Character, Character>(); public static boolean isBalanced(String expression) { Stack<Character> st = new Stack<Character>(); for(int i=0; i < expression.length();i++){ char bracket = expression.charAt(i); if(!st.empty()) { char lastBracket = st.peek(); if(bracketsMap.get(lastBracket) == bracket){ st.pop(); }else{ st.push(bracket); } }else{ st.push(bracket); } } if(!st.empty()){ return false; } return true; } public static void main(String[] args) { bracketsMap.put('(',')'); bracketsMap.put(')','('); bracketsMap.put('{','}'); bracketsMap.put('}','{'); bracketsMap.put('[',']'); bracketsMap.put(']','['); Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int a0 = 0; a0 < t; a0++) { String expression = in.next(); System.out.println( (isBalanced(expression)) ? "YES" : "NO" ); } } }