NEED HELP WITH THIS (DO IT IN JAVA PLEASE) Consider an expression that contains
ID: 3577659 • Letter: N
Question
NEED HELP WITH THIS (DO IT IN JAVA PLEASE)
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 isBalanced(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
import java.util.*;
public class ParenthesisMatching
{
//function to check Balanced
public static boolean Balanced(String s) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
boolean flag=Balanced(s);
if(flag)
System.out.println("Balanced");
else
System.out.println("Not Balanced");
}
}
==============================================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac ParenthesisMatching.java
akshay@akshay-Inspiron-3537:~/Chegg$ java ParenthesisMatching
abc{de(fg){ijk}{l{m[n]}}o[p]}qr
Balanced
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.