HackerRank Java- Stack




A string containing only parentheses is balanced if the following is true: 1. if it is an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also correct.

Examples of some correctly balanced strings are: "{}()", "[{()}]", "({()})"

Examples of some unbalanced strings are: "{}(", "({)}", "[[", "}{" etc.

Given a string, determine if it is balanced or not.



  1. import java.util.*;
  2. class Solution {
  3. private static boolean isBalanced(String expression) {
  4. if ((expression.length() & 1) == 1)
  5. return false;
  6. char[] brackets = expression.toCharArray();
  7. Stack<Character> stack = new Stack<>();
  8. for (char bracket : brackets)
  9. switch (bracket) {
  10. case '{':
  11. stack.push('}');
  12. break;
  13. case '(':
  14. stack.push(')');
  15. break;
  16. case '[':
  17. stack.push(']');
  18. break;
  19. default:
  20. if (stack.empty() || bracket != stack.peek())
  21. return false;
  22. stack.pop();
  23. }
  24. return stack.empty();
  25. }
  26. public static void main(String[] argh) {
  27. Scanner sc = new Scanner(System.in);
  28. while (sc.hasNext()) {
  29. String expression = sc.next();
  30. System.out.println(isBalanced(expression) ? "true" : "false");
  31. }
  32. sc.close();
  33. }
  34. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube