Consider an expression that contains grouping symbols. The grouping symbols are
ID: 3576639 • Letter: C
Question
Consider an expression that contains grouping symbols. The grouping symbols are parentheses, {}, []. Expressions are considered to be balanced if their grouping symbols follow the following rules: each left symbol must be followed by a right symbol with some data in between (ie. you can't have an empty pair like []) if pairs are nested, one pair must be completely nested within another. Here is an example of a balanced expression: abc{de(fg) {ijk}{l{m[n]}}o[p]}qr Here is an example where the grouping symbols are not balanced: abc{(def}} {ghij{kl}m] Write a method with signature boolean is Balanced(String s) that returns true if the grouping symbols within the string are properly balanced. Use a stack in your solution. You may assume that each symbol is just one character and that there are no spaces, as in the examples above.Explanation / Answer
Hi, Please find my implemeentation.
Please let me know in case of any issue.
import java.util.*;
import java.io.*;
public class ExpressionBalanceCheck {
public static void main(String[] args) {
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many expression do you wnat to test ? ");
String line = br.readLine();
int N = Integer.parseInt(line);
int i=0;
while (i<N)
{ if (isBalanced(br.readLine()))
System.out.println("balanced");
else
System.out.println("not balanced");
i++;
}
}
catch (IOException e)
{
}
}
public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
boolean result = true;
int n = s.length()-1;
for (int i = 0; i <=n; i++) {
char c = s.charAt(i);
switch (c) {
case ')':
if ((Character) stack.pop() != '(') {
return false;
}
break;
case '}':
if ((Character) stack.pop() != '{') {
return false;
}
break;
case ']':
if ((Character) stack.pop() != '[') {
return false;
}
break;
case '(':
// s.charAt(i+1) == ')' => to test empty parenthesis
if(( i == n) || (s.charAt(i+1) == ')'))
return false;
stack.push(c);
break;
case '{':
// s.charAt(i+1) == '}' => to test empty parenthesis
if(( i == n) || (s.charAt(i+1) == '}'))
return false;
stack.push(c);
break;
case '[':
// s.charAt(i+1) == ']' => to test empty parenthesis
if(( i == n) || (s.charAt(i+1) == ']'))
return false;
stack.push(c);
break;
default:
}
}
return result;
}
}
/*
Sample run:
How many expression do you wnat to test ? 4
{efefef(ferf)fef}
balanced
dfewf{edfefe}()fewf[ef3e]
not balanced
{(fefef)fefewff[fdefe]fefef}
balanced
{}dfdefeefe{}
not balanced
*/