
Java Stack Hackerrank Solution
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
Code Solution:
//Java Stack Hackerrank Solution import java.util.*; class Solution{ public static void main(String []argh) { Scanner sc = new Scanner(System.in); Stack <String> stk=new Stack <>(); while (sc.hasNext()) { String input=sc.next(); //Complete the code while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length()); System.out.println(input.isEmpty()); } } } //Java Stack Hackerrank Solution
Disclaimer: This problem is originally created and published by HackerRank, we only provide solutions to this problem. Hence, doesn’t guarantee the truthfulness of the problem. This is only for information purposes.