To review stacks Directions : Write Java code that prompts the user for a string
ID: 3862691 • Letter: T
Question
To review stacks
Directions :
Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced. Grouping characters are ( and ), [ and ], and { and }. I got the basic idea for this problem from HackerRank. It’s also a very common interview question.
Examples
Enter the expression:{[()]} {[()]}
is balanced
Enter the expression: {()()} {()()}
is balanced
Enter the expression: {([[])} {([[])}
is not balanced
Enter the expression: {([)]} {([)]}
is not balanced
Explanation / Answer
import java.util.Stack;
import java.util.Scanner;
public class CheckBalancedParentesisMain {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String expr=a.nextLine();
//String checkBalancedParentesis(expr);
String checkBalancedExpr1=checkBalancedParentesis(expr);
public static String checkBalancedParentesis(String expr)
{
if (expr.isEmpty())
return "Balanced";
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < expr.length(); i++)
{
char current = expr.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return "Not Balanced";
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return "Not Balanced";
}
}
return stack.isEmpty()?"Balanced":"Not Balanced";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.