In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added.(Wikipedia)
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.*;
class Solution {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
Stack<String> Symbol = new Stack<String>();
while (sc.hasNext()) {
String input = sc.next();
boolean ans = true;
for (String x : input.split("")) {
try {
if ((x.equals(")")) || (x.equals("}")) || (x.equals("]"))) {
Symbol.pop();
} else {
Symbol.add(input);
}
} catch (EmptyStackException e) {
ans = false;
break;
}
}
if ((ans == true) && (Symbol.size() == 0)) {
System.out.println("true");
Symbol.clear();
} else {
System.out.println("false");
Symbol.clear();
}
}
}
}
SOLUTION : – To optimize the given code, you can make a few changes:
- 1. Use a
Stack<Character> instead of Stack<String>
since you are dealing with single characters. - 2. Instead of using
String.split("")
to split the input into characters, you can directly iterate over the characters of the input string usingcharAt(i)
. - 3. Use a more descriptive variable name instead of
Symbol
for the stack.
Here’s the optimized version of the code:
import java.util.*;
class Solution {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
Stack<Character> stack = new Stack<>();
boolean isValid = true;
for (int i = 0; i < input.length(); i++) {
char current = input.charAt(i);
if (current == '(' || current == '{' || current == '[') {
stack.push(current);
} else if (current == ')' || current == '}' || current == ']') {
if (stack.isEmpty() || !isMatching(stack.pop(), current)) {
isValid = false;
break;
}
}
}
if (isValid && stack.isEmpty()) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
private static boolean isMatching(char left, char right) {
return (left == '(' && right == ')') ||
(left == '{' && right == '}') ||
(left == '[' && right == ']');
}
}
FOLLOW FOR MORE QUESTIONS AND SOLUTIONS |Â DIGIT WOOD
Leave a Reply