Java Stack || Hackerrank Solution

 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.

Input Format

There will be multiple lines in the input file, each having a single non-empty string. You should read input till end-of-file.

The part of the code that handles input operation is already provided in the editor.

Output Format

For each case, print 'true' if the string is balanced, 'false' otherwise.

Sample Input

{}()
({()})
{}(
[]

Sample Output

true
true
false
true
  • Solution:
import java.util.Scanner; import java.util.HashMap; import java.util.ArrayDeque; // ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation class Solution { public static void main(String[] args) { /* Create HashMap to match opening brackets with closing brackets */ HashMap<Character, Character> map = new HashMap(); map.put('(', ')'); map.put('[', ']'); map.put('{', '}'); /* Test each expression for validity */ Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String expression = scan.next(); System.out.println(isBalanced(expression, map) ? "true" : "false" ); } scan.close(); } private static boolean isBalanced(String expression, HashMap<Character, Character> map) { if ((expression.length() % 2) != 0) { return false; // odd length Strings are not balanced } ArrayDeque<Character> deque = new ArrayDeque(); // use deque as a stack for (int i = 0; i < expression.length(); i++) { Character ch = expression.charAt(i); if (map.containsKey(ch)) { deque.push(ch); } else if (deque.isEmpty() || ch != map.get(deque.pop())) { return false; } } return deque.isEmpty(); } }

🙏THANKS FOR VISIT🙏

Java Stack || Hackerrank Solution Java Stack || Hackerrank Solution Reviewed by CodexRitik on November 07, 2020 Rating: 5

No comments:

Powered by Blogger.