Undefined char in output of bracket-matching program using custom stack - java

My Java Program is below. It's my training exercise. The one implements stack stucture for special type of string parsing(string with delimiter).
This delimiter-matching program works by reading characters from the string one at
a time and placing opening delimiters when it finds them, on a stack. When it reads
a closing delimiter from the input, it pops the opening delimiter from the top of the
stack and attempts to match it with the closing delimiter. If they’re not the same
type (there’s an opening brace but a closing parenthesis, for example), an error
occurs. Also, if there is no opening delimiter on the stack to match a closing one, or
if a delimiter has not been matched, an error occurs. A delimiter that hasn’t been
matched is discovered because it remains on the stack after all the characters in the
string have been read.
I use Eclipse. My output is here:
Please enter String:
{}
ch0 = {
ch1 = }
chLabel1 = **UNDEFINED CHAR(SQUARE WITH QUESTION MARK INSIDE IT)**
Error at }**
Could you explain value of chLabel?
As I understand operator "|" (here, cause two operands have boolean type) - is "lazy", shortcut version of "||" operator. I've tested the program after substitution "|" for "||"-result is the same.
public class MyStack {
private int top=0;
private int maxSize=0;
private char[] charArray=null;
public MyStack(int size){
maxSize=size;
top=0;
charArray=new char[maxSize];
}
public void push(char ch){
charArray[top++]=ch;
}
public char pop(){
return charArray[top--];
}
public boolean isEmpty(){
if(top==0)
return true;
else return false;
}
public boolean isFull(){
if(top==(maxSize-1))
return true;
else return false;
}
}
class StringParse {
private String stringForParsing = null;
public StringParse(String string) {
this.stringForParsing = string;
}
public void parser() {
char[] chArr = stringForParsing.toCharArray();
MyStack mySt = new MyStack(chArr.length);
for (int i = 0; i < chArr.length; i++) {
char ch = chArr[i];
switch (ch) {
case '{':
case '(':
case '[':
mySt.push(ch);
System.out.println("ch" + i + " = " + ch);
break;
case '}':
case ')':
case ']':
if (mySt.isEmpty())
System.out.println("Error at" + ch);
else {
char chLabel = mySt.pop();
System.out.println("ch" + i + " = " + ch);
System.out.println("chLabel" + i + " = " + chLabel);
if ((chLabel == '{') && (ch == '}') | (chLabel == '(') && (ch == ')') | (chLabel == '[') && (ch == ']'))
break;
else {
System.out.println("Error at " + ch);
break;
} // end of second else
} //end of first else
default:
break;
} //end of switch
} //end of parser method
}
} //end of class
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("Please enter String:");
String s = br.readLine();
StringParse strP = new StringParse(s);
strP.parser();
}
}

There are two problems:
There's an error with the pop function.
Consider doing one push and then one pop:
top = 0
push
insert at position 0
set top to 1
pop
get position 1 (not set yet!)
set top to 0
You need to use pre-decrement instead of post-decrement, so charArray[top--] should be charArray[--top].
With this change I get chLabel1 = {.
Reiterating what I said in the comments...
| has higher precendence than &&(as opposed to || which has lower precedence) (see this)‌​,
thus a && b | c && d is the same as a && (b | c) && d,
as opposed to a && b || c && d which would be (a && b) || (c && d).
When changing the |'s to ||'s, I no longer get Error at }.

There may be a problem with your MyStack class
Using java.util.Stack gives me no error, just a "chLabel1 = {"
Error at } can be resolved by following Dukeling's advice and using || instead of |:
(chLabel == '{') && (ch == '}') || (chLabel == '(') && (ch == ')') || (chLabel == '[') && (ch == ']')
So, it looks like your code in MyStack.pop() doesn't return a valid char. I'll need to see your MyStack code to help further.

Related

Is there a better way to write a java code for detecting valid parentheses in a String?

I tried to solve a problem in leetcode and im not able to pass all the test cases. I tried to use stack. Whenever there is an open parenthesis, I push it into the stack and whenever there is a close parentheses, I check and pop if the correct open parenthesis is present on the top of the stack.
I check if the stack is empty in the last
Problem statement:
Given a string containing just
the characters '(', ')', '{', '}', '[' and ']', determine if the
input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Stack<Character> stk = new Stack<Character>();
boolean check = true;
char temp;
if(s.length() == 1)
{
return false;
}
else if(s.length() == 0)
{
return true;
}
else
{
for(int i = 0 ; i < s.length() ; i++)
{
temp = s.charAt(i);
if(temp == '{' || temp == '(' || temp == '[')
{
stk.push(temp);
}
else if(temp == '}')
{
if(stk.peek() == '{')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ')')
{
if(stk.peek() == '(')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ']')
{
if(stk.peek() == '[')
{
stk.pop();
}
else
{
check = false;
}
}
}
if(check == false && stk.empty() == false)
{
return false;
}
else
{
return true;
}
}
You have simply not taken in consideration cases such as
()), where the stack can be empty when you receive a new closing paranthesis.
Simply add
!stk.isEmpty()&&
before each
stk.peek()
It's generally a good idea when working with vectors, matrix, etc. to verify if the element is within bounds and exists(or give internal reasoning as to why it isn't and why at least a check is necessary).
Also, sometimes you can have stuff such as
(, where the check doesn't meet a mismatching closing paranthesis to turn it into false. However, there is a mismatching opening paranthesis.
So the final part of the code has to be
if(check == false || stk.empty() == false)
instead of &&, I put ||
I've run it on the site and it works :) .
This code works on Leetcode. I've modified it so that instead of setting check to false, it just immediately returns false, since there's no point going through the whole string. It also checks if the stack is empty at each iteration. To avoid failing when the input starts with a closing parentheses, square bracket, or curly brace, it pushes the first character of the string onto the stack at the very start.
I've also improved it a bit by rejecting strings of odd lengths at the very start, which makes it run faster than 98.69% of all submissions to the Leetcode problem.
Stack<Character> stk = new Stack<Character>();
char temp;
int len = s.length();
if(len == 0) {
return true;
} else if (len % 2 == 1) {
return false;
}
stk.push(s.charAt(0));
for(int i = 1; i < len; i++) {
temp = s.charAt(i);
switch (temp) {
case '{':
case '(':
case '[':
stk.push(temp);
break;
case '}':
if (stk.peek() == '{') {
stk.pop();
break;
} else return false;
case ')':
if (stk.peek() == '(') {
stk.pop();
break;
} else return false;
case ']':
if (stk.peek() == '[') {
stk.pop();
break;
} else return false;
}
if (stk.isEmpty()) break;
}
return stk.isEmpty();
I hope you don't mind that I replaced your if-statements with a switch block. It's pretty much the same, but it looks clearer to me, at least. You can always change it back though, it'll work the same.
This seems to work fine:
public boolean isValid(String s) {
int n = s.length();
if (n == 0) return true;
if (n % 2 == 1) return false;
Stack<Character> st = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '{' || c == '[' || c == '(') {
st.push(c);
} else if (st.isEmpty()) { // no opening bracket stored
return false;
} else {
char prev = st.pop();
switch(c) { // matching open and close bracket
case '}': if (prev != '{') return false; else break;
case ']': if (prev != '[') return false; else break;
case ')': if (prev != '(') return false; else break;
}
}
}
return st.isEmpty(); // stack must be empty in the end - all pairs matched
}

Verify whether the next char is the same as first char

I found a problem and i tried my logic but i failed to get to the solution.
This is the problem i am trying to solve in java.
For every opening brace (i.e., (, {, or [), there is a matching closing brace (i.e., ), }, or ]) of the same type (i.e., (matches ), { matches }, and [ matches ]). An opening brace must appear before (to the left of) it’s matching closing brace. For example, ]{}[ is not balanced.
No unmatched braces lie between some pair of matched braces. For example, ({[]}) is balanced, but {[}] and [{)] are not balanced.
I want to write java code which would take such a string input of braces and output whether it is balanced or not.
I am not able to apply logic for this kind of code, i tried however it was not even close to expectations. Please provide with some logic. I know this is not a homework completion site but i am stuck on the logic of this problem. a code snippet would be appreciated.
This has nothing to do with java. You need to use a stack to keep track of the order in which you encounter the brackets.
Algorithm-
loop over the input string.
If the current character is an opening bracket, push it in the stack
It it is a closing bracket, pop an element from the stack and if it is not the corresponding opening bracket to the current closing bracket then it is not balanced.
After traversing the string, if there is an opening bracket in the stack then it is not balanced.
Try this.
public static boolean isBalanced(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
switch (c) {
case '(': stack.push(')'); break;
case '[': stack.push(']'); break;
case '{': stack.push('}'); break;
case ')': case ']': case '}':
if (stack.isEmpty() || !stack.pop().equals(c))
return false;
break;
}
}
return stack.isEmpty();
}
No switch version:
public static boolean isBalanced(String s) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '(')
stack.push(')');
else if (c == '[')
stack.push(']');
else if (c == '{')
stack.push('}');
else if (c == ')' || c == ']' || c == '}')
if (stack.isEmpty() || !stack.pop().equals(c))
return false;
}
return stack.isEmpty();
}
Another way to solve this problem.
This can be solved using Stack Datastructure.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.next(); //input string -> eg : {{[[(())]]}}
boolean check = Paran(string);
if(check){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
//function that checks brackets are balanced or not
public static boolean Paran(String string){
//create a stack
Stack<Character> s = new Stack<Character>();
//check if string is empty
//if string is empty then Balanced
if(string.length() == 0){
return true;
}
//if string is not empty, go through each character
for(int i = 0; i< string.length(); i++){
//fetch each character
char current = string.charAt(i);
//check if that character id any of {([
// if yes push on to the stack
if(current == '[' || current == '{' || current == '('){
s.push(current);
}
//check if that character id any of }])
if(current == '}' || current == ']' || current == ')'){
//check stack is empty
//if yes then return false
if(s.isEmpty()){
return false;
}
//else fetch top most item
char pre = s.peek();
if((current == '}' && pre == '{') || (current == ']' && pre == '[') || (current == ')' && pre == '(')){
s.pop();
}
else{
return false;
}
}
}
return s.isEmpty();
}
}
Hope this helps

How to use variables in stack?

I'm trying to write a calc program that finds the infix. In addition the user will input numbers for the x variable and the program will solve it. My program works but it only solves it the first time. The following times it gives the same answer as the first time.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
class Stack {
char a[] = new char[100];
int top = -1;
void push(char c) {
try {
a[++top] = c;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Stack full , no room to push , size=100");
System.exit(0);
}
}
char pop() {
return a[top--];
}
boolean isEmpty() {
return (top == -1) ? true : false;
}
char peek() {
return a[top];
}
}
public class intopost {
static Stack operators = new Stack();
public static void main(String argv[]) throws IOException {
String infix;
// create an input stream object
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
// get input from user
System.out.print("\nEnter the algebraic expression in infix: ");
infix = keyboard.readLine();
String postFx = toPostfix(infix);
// output as postfix
System.out.println("The expression in postfix is:" + postFx);
if (postFx.contains("x")) {
String line = "";
do {
System.out.println("Enter value of X : ");
line = keyboard.readLine();
if (!"q".equalsIgnoreCase(line)) {
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
} while (!line.equals("q"));
} else {
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
}
private static String toPostfix(String infix)
// converts an infix expression to postfix
{
char symbol;
String postfix = "";
for (int i = 0; i < infix.length(); ++i)
// while there is input to be read
{
symbol = infix.charAt(i);
// if it's an operand, add it to the string
if (symbol != ' ') {
if (Character.isLetter(symbol) || Character.isDigit(symbol))
postfix = postfix + " " + symbol;
else if (symbol == '(')
// push (
{
operators.push(symbol);
} else if (symbol == ')')
// push everything back to (
{
while (operators.peek() != '(') {
postfix = postfix + " " + operators.pop();
}
operators.pop(); // remove '('
} else
// print operators occurring before it that have greater
// precedence
{
while (!operators.isEmpty() && !(operators.peek() == '(')
&& prec(symbol) <= prec(operators.peek()))
postfix = postfix + " " + operators.pop();
operators.push(symbol);
}
}
}
while (!operators.isEmpty())
postfix = postfix + " " + operators.pop();
return postfix.trim();
}
static int prec(char x) {
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
}
class EvaluateString {
public static int evaluate(String expression) {
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
LinkedList<Integer> values = new LinkedList<Integer>();
// Stack for Operators: 'ops'
LinkedList<Character> ops = new LinkedList<Character>();
for (int i = 0; i < tokens.length; i++) {
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9') {
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0'
&& tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')') {
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*'
|| tokens[i] == '/') {
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.isEmpty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.isEmpty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of 'values' contains result, return it
return values.pop();
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
There is a mistake inside while loop in main method. See snippet below.
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
Here postFx = postFx.replaceAll("x", line); you lost reference to postfix form that contains variable x. Subsequent calls of replaceAll doesn't have any effect. So expression with first entered value is evaluated.
You can easily fix it by replacing code above with
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx.replaceAll("x", line)));

Why isn't this program running properly? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
The assignment was to create a postfix to infix converter using Stacks. The program compiles properly but when I tried to make a demo class, I received a null point exception line 32. Please share any observations, better coding conventions, or solutions.
import java.util.Stack;
public class PostfixtoInfix {
private String expression;
private Stack<Character> s;
Character pOpen = new Character('(');
Character pClose = new Character(')');
public String PostfixtoInfix(String e) {
expression = e;
String output = "";
for (int i = 0; i < e.length(); i++) {
char currentChar = e.charAt(i);
if (isOperator(currentChar)) {
while (!s.empty() && s.peek() != pOpen
&& hasHigherPrecedence(s.peek(), currentChar)) {
output += s.peek();
s.pop();
}
s.push(currentChar);
} else if (isOperand(currentChar)) {
output += currentChar;
} else if (currentChar == '(') {
s.push(currentChar);
} else if (currentChar == ')') {
while (!s.empty() && s.peek() != pClose) {
output += s.peek();
s.pop();
}
}
while (!s.empty()) {
output += s.peek();
s.pop();
}
}
return output;
}
public boolean isOperator(char c) {
if (c == '+' || c == '-' || c == '/' || c == '*' || c == '^')
return true;
return false;
}
public boolean isOperand(char c) {
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
return false;
}
public int getOperatorWeight(char operator) {
int weight = -1;
switch (operator) {
case '+':
case '-':
weight = 1;
break;
case '*':
case '/':
weight = 2;
break;
case '^':
weight = 3;
}
return weight;
}
public boolean hasHigherPrecedence(char operator1, char operator2) {
int op1 = getOperatorWeight(operator1);
int op2 = getOperatorWeight(operator2);
if (op1 == op2) {
if (isRightAssociative(operator1))
return false;
else
return true;
}
return op1 > op2 ? true : false;
}
public boolean isRightAssociative(char op) {
if (op == '^')
return true;
return false;
}
}
To fix the NPE initialize your objects. Unlike C++, Stack<Character> s; is equivalent to Stack<Character> s = null;; not to Stack<Character> s = new Stack<>();!
Beware of == and != not behaving as you might expect for boxed objects.
Character a = new Character('A');
Character aa = new Character('A');
System.out.println(a == aa);
gives the (correct!) answer false.
They are different objects. If you want to compare for equality, use either:
System.out.println(a.equals(aa));
System.out.println((char)a==(char)aa);
The first uses an explicit method for comparing the object contents. The second one avoids this problem by using non-object primitives, where equality is bitwise, not reference-equality.
It appears that you declare a private member s, never assign anything to it, and then attempt to use it in expressions like s.empty() and s.pop(). If nothing is ever assigned to s, then it is null, and attempting to call a method on it will result in a NullPointerException.
To create an empty stack, you probably want to change the declaration to:
private Stack <Character> s = new Stack<Character>();
First of all, you have a method looking like a constructor:
public String PostfixtoInfix(String e) {
try changing it to something else, like:
public String transform(String e) {
Second, your s field never gets assigned a stack. Put
s = new Stack<Character>();
in your constructor. Also, new Character('a') != new Character('a'), because that will bypass automatic (pillowweight cached) boxing. Use instead just simple chars as pOpen and pClose.
Your access modifier may be preventing the program to access the stack.
Change:
private Stack <Character> s;
to:
protected Stack <Character> s;
Read more here

Java program to read parenthesis, curly braces, and brackets

I'm supposed to create a Java program which reads expressions that contain, among other items, braces { },
brackets [ ], and parentheses ( ). My program should be properly
nested and that ‘(‘ matches ‘)’, ‘[‘ matches ‘]’, and ‘{’ matches ‘}‘ The
program should be terminated by a ‘$’ at the beginning of an input line.
These are supposed to be sample runs of my program:
Enter an Expression:
A[F + X {Y – 2}]
The expression is Legal
Enter an Expression:
B+[3 – {X/2})*19 + 2/(X – 7)
ERROR—‘]’ expected
Enter an Expression:
()) (
ERROR--‘)’ without ‘(‘
$
I created a class called BalancedExpression and a driver called ExpressionChecker.
I completed my BalancedExpression class. But, I'm having trouble setting up my driver to print out an expression using an InputStreamReader and a BufferedReader. The only thing I was able to figure out was how to terminate my program by letting the user enter a $.
Here is my code so far:
Balanced Expression class:
public class BalancedExpression
{
public BalancedExpression() // Default Constructor
{
sp = 0; // the stack pointer
theStack = new int[MAX_STACK_SIZE];
}
public void push(int value) // Method to push an expression into the stack
{
if (!full())
theStack[sp++] = value;
}
public int pop() // Method to pop an expression out of the stack
{
if (!empty())
return theStack[--sp];
else
return -1;
}
public boolean full() // Method to determine if the stack is full
{
if (sp == MAX_STACK_SIZE)
return true;
else
return false;
}
public boolean empty() // Method to determine if the stack is empty
{
if (sp == 0)
return true;
else
return false;
}
public static boolean checkExpression(String ex) // Method to check Expression in stack
{
BalancedExpression stExpression = new BalancedExpression();
for(int i = 0; i< MAX_STACK_SIZE; i++)
{
char ch = ex.charAt(i);
if(ch == '(' || ch == '{' || ch == '[')
stExpression.push(ch);
else if(ch == ')' && !stExpression.empty() && stExpression.equals('('))
stExpression.pop();
else if(ch == '}' && !stExpression.empty() && stExpression.equals('{'))
stExpression.pop();
else if(ch == ']' && !stExpression.empty() && stExpression.equals('['))
stExpression.pop();
else if(ch == ')' || ch == '}' || ch == ']' )
return false;
}
if(!stExpression.empty())
return false;
return true;
}
private int sp;
private int[] theStack;
private static final int MAX_STACK_SIZE = 6;
}// End of class BalancedExpression
My Driver Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExpressionChecker
{
public static void main(String[] args)
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
BalancedExpression exp = new BalancedExpression();
String expression = "";
do
{
try{
System.out.print("Enter an Expression: ");
expression = console.readLine();
if("$".equals(expression))
break;
}catch(Exception e){
System.out.println("IO error:" + e);
}
}while(!expression.equals(""));// End of while loop
}
}// End of class ExpressionChecker
Can anyone please help me develop my driver program to print out an output similar to the sample example?
Any help is appreciated. Thanks!
In the if statements in checkExpression method you are using
stExpression.equals()
while what you want to do is to 'peek' at the value on the top of the stack.
Adding simple method that pops the value, pushes it back and returns it should solve the problem(at least this part).
Here is a very short example where you can do the above check very easily :) We have Stack class in Java, it will make the program very easy. Please find below the simple code for this question:
package com.test;
import java.util.Scanner;
import java.util.Stack;
public class StackChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enete an expression : ");
String expr = sc.nextLine();
if(checkvalidExpression(expr)){
System.out.println("The Expression '"+expr+"' is a valid expression!!!");
}
else{
System.out.println("The Expression '"+expr+"' is a NOT a valid expression!!!");
}
}
public static boolean checkvalidExpression(String expr){
Stack<Character> charStack = new Stack<Character>();
int len = expr.length();
char exprChar = ' ';
for(int indexOfExpr = 0; indexOfExpr<len; indexOfExpr++){
exprChar = expr.charAt(indexOfExpr);
if(exprChar == '(' || exprChar == '{' || exprChar == '['){
charStack.push(exprChar);
}
else if(exprChar == ')' && !charStack.empty()){
if(charStack.peek() == '('){
charStack.pop();
}
}
else if(exprChar == '}' && !charStack.empty()){
if(charStack.peek() == '{'){
charStack.pop();
}
}
else if(exprChar == ']' && !charStack.empty()){
if(charStack.peek() == '['){
charStack.pop();
}
}
else if(exprChar == ')' || exprChar == '}' || exprChar == ']' ){
return false;
}
}
if(!charStack.empty())
return false;
return true;
}
}

Categories