Problem:
Write a java method that checks if a character is balanced using stacks.
Output:
Not applicable.
Solution:
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
public class ParanChecker
{
public static void main(String[] args)
{
//We assume that the Character is balanced from the beginning
boolean balanced = true;
String OPEN = "([{";
String CLOSE = ")]}";
Scanner scan = new Scanner(System.in);
Stack <Character> s = new Stack<Character>();
System.out.println("Enter your expression:");
String expression = scan.nextLine();
try
{
int index = 0;
while (balanced && index < expression.length())
{
char nextCh = expression.charAt(index);
if ( OPEN.indexOf(nextCh) != -1 )
s.push(nextCh);
else if ( CLOSE.indexOf(nextCh) != -1)
{
char topCh = s.pop();
balanced = (OPEN.indexOf(topCh) == CLOSE.indexOf(nextCh));
}
index++;
}
}
catch(EmptyStackException emptyStackException)
{
balanced = false;
}
if ( balanced && s.empty())
System.out.println("The Character is balanced");
else
System.out.println("The Character is not balanced");
}
}
No comments :
Post a Comment