String Balancing program with Java HackerRank Solutions
Task
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.
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.*;
import java.util.regex.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
boolean isBalanced = isBalancedString(input);
System.out.println(isBalanced);
}
}
private static boolean isBalancedString(String line)
{
Stack<Character> stack = new Stack<>();
for (char c : line.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}
Steps involved in this solution:
1. The code begins by importing the necessary packages: java.util.*: This package contains classes for data structures like Stack
. java.util.regex.*: This package includes classes for regular expressions, although it's not directly used in this code.
2. The code defines a class named Solution. This class contains the main method and the isBalancedString() method.
3. The main method is the entry point of the program. It creates a Scanner object to read input from the standard input (System.in).
4. The code uses a while loop to read input as long as there is more input available (provided by sc.hasNext()
).
5. Inside the loop, it reads the next input string using sc.next() and stores it in the input variable.
6. It calls the isBalancedString() method with the input string to check whether it is a balanced string.
7. This method checks if the input string is balanced by examining its symbols. It uses a Stack<Character> to keep track of opening symbols and verifies that they have matching closing symbols. It iterates through the characters of the input string.
8. If the current character is an opening symbol ((
, {
, or [
), it pushes it onto the stack. If the character is a closing symbol ()
, }
, or ]
), it checks if the stack is empty. If it is, this means the string is unbalanced, and it returns false. If the stack is not empty, it pops the top character from the stack and checks if it matches the current closing symbol. If they don't match, it returns false.
9. After processing all characters, it checks whether the stack is empty. If the stack is empty, it means that all opening symbols had matching closing symbols, and it returns true. Otherwise, it returns false.
10. The result of the isBalancedString() method is printed to the standard output, which indicates whether the input string is balanced.