I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expressio
public class StackProb {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Boolean> list = new ArrayList<>();
while (sc.hasNextLine()) {
String s=sc.nextLine();
if(!s.isEmpty()) {
list.add(isBalanced(s));
//System.out.println(isBalanced(s));
}else {
sc.close();
break;
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + " ");
}
}
private static boolean isBalanced(String s) {
boolean res = false;
Stack<Character> stack = new Stack();
int countA = 0;
int countB = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='{' || s.charAt(i)=='(' || s.charAt(i)=='[') {
stack.push(s.charAt(i));
countA++;
}
if(s.charAt(i)=='}' || s.charAt(i)==')' || s.charAt(i)==']') {
stack.push(s.charAt(i));
countB++;
}
if(stack.firstElement()=='}' || stack.firstElement()==')' || stack.firstElement()==']') {
countB++;
}
}
if(countA==countB) {
return true;
}
return false;
}
}
This can be used. Passes all the tests.
static String isBalanced(String s) {
if(null == s){
return "";
}
Stack<Character> bracketStack = new Stack<>();
int length = s.length();
if(length < 2 || length > 1000){
return "NO";
}
for(int i = 0; i < length; i++){
Character c= s.charAt(i);
if(c == '(' || c == '{' || c == '[' ){
bracketStack.push(c);
} else {
if(!bracketStack.isEmpty()){
char cPop = bracketStack.pop();
if(c == ']' && cPop!= '['){
return "NO";
}
if(c == ')' && cPop!= '('){
return "NO";
}
if(c == '}' && cPop!= '{'){
return "NO";
}
} else{
return "NO";
}
}
}
if(bracketStack.isEmpty()){
return "YES";
} else {
return "NO";
}
}
I hope this code can help:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
public static void main(String[] args) {
System.out.println("is balanced : "+isBalanced("(){}[]<>"));
System.out.println("is balanced : "+isBalanced("({})[]<>"));
System.out.println("is balanced : "+isBalanced("({[]})<>"));
System.out.println("is balanced : "+isBalanced("({[<>]})"));
System.out.println("is balanced : "+isBalanced("({})[<>]"));
System.out.println("is balanced : "+isBalanced("({[}])[<>]"));
System.out.println("is balanced : "+isBalanced("([{})]"));
System.out.println("is balanced : "+isBalanced("[({}])"));
System.out.println("is balanced : "+isBalanced("[(<{>})]"));
System.out.println("is balanced : "+isBalanced("["));
System.out.println("is balanced : "+isBalanced("]"));
System.out.println("is balanced : "+isBalanced("asdlsa"));
}
private static boolean isBalanced(String brackets){
char[] bracketsArray = brackets.toCharArray();
Stack<Character> stack = new Stack<Character>();
Map<Character, Character> openingClosingMap = initOpeningClosingMap();
for (char bracket : bracketsArray) {
if(openingClosingMap.keySet().contains(bracket)){
stack.push(bracket);
}else if(openingClosingMap.values().contains(bracket)){
if(stack.isEmpty() || openingClosingMap.get(stack.pop())!=bracket){
return false;
}
}else{
System.out.println("Only < > ( ) { } [ ] brackets are allowed .");
return false;
}
}
return stack.isEmpty();
}
private static Map<Character, Character> initOpeningClosingMap() {
Map<Character, Character> openingClosingMap = new HashMap<Character, Character>();
openingClosingMap.put(Character.valueOf('('), Character.valueOf(')'));
openingClosingMap.put(Character.valueOf('{'), Character.valueOf('}'));
openingClosingMap.put(Character.valueOf('['), Character.valueOf(']'));
openingClosingMap.put(Character.valueOf('<'), Character.valueOf('>'));
return openingClosingMap;
}
Simplifying and making readable. Using One Map only and minimum conditions to get desired result.
Code snippet for implementing matching parenthesis using java.util.Stack
data structure -
//map for storing matching parenthesis pairs
private static final Map<Character, Character> matchingParenMap = new HashMap<>();
//set for storing opening parenthesis
private static final Set<Character> openingParenSet = new HashSet<>();
static {
matchingParenMap.put(')','(');
matchingParenMap.put(']','[');
matchingParenMap.put('}','{');
openingParenSet.addAll(matchingParenMap.values());
}
//check if parenthesis match
public static boolean hasMatchingParen(String input) {
try {
//stack to store opening parenthesis
Stack<Character> parenStack = new Stack<>();
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
//if an opening parenthesis then push to the stack
if(openingParenSet.contains(ch)) {
parenStack.push(ch);
}
//for closing parenthesis
if(matchingParenMap.containsKey(ch)) {
Character lastParen = parenStack.pop();
if(lastParen != matchingParenMap.get(ch)) {
return false;
}
}
}
//returns true if the stack is empty else false
return parenStack.isEmpty();
}
catch(StackOverflowException s) {}
catch(StackUnderflowException s1) {}
return false;
}
I have explained the code snippet and the algorithm used on blog http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
It's important to use a stack to push opening symbols onto it, then when you come across a closing brace you pop the element off the top of the stack and then you check it to see if it matches the type of closing brace. Here is a java implementation.
import java.util.Stack;
public class Balanced {
public static void main (String [] args)
{
String test_good = "()(){}{}{()}";
String test_bad = "((({}{}))()";
System.out.println(checkBalanced(test_good));
System.out.println(checkBalanced(test_bad));
}
public static boolean checkBalanced(String check)
{
Stack<Character> S = new Stack<Character>();
for(int a = 0; a < check.length(); a++)
{
char let = check.charAt(a);
if(let == '[' || let == '{' || let == '(')
S.push(let);
else if(let == ']' || let == '}' || let == ')')
{
if(S.empty())
return false;
switch(let)
{
// Opening square brace
case ']':
if (S.pop() != '[')
return false;
break;
// Opening curly brace
case '}':
if (S.pop() != '{')
return false;
break;
// Opening paren brace
case ')':
if (S.pop() != '(')
return false;
break;
default:
break;
}
}
}
if(S.empty())
return true;
return false;
}
}