At Westonci.ca, we connect you with the answers you need, thanks to our active and informed community. Explore a wealth of knowledge from professionals across various disciplines on our comprehensive Q&A platform. Connect with a community of professionals ready to help you find accurate solutions to your questions quickly and efficiently.

Write a function int checkBalance(char exp[]); that can take an expression as input and check whether the parenthesis used in that expression are valid or invalid. It returns 1 if it is valid, and returns 0 if it is not valid.For example, the following expressions are valid: [ A * {B (C D)}] and [{()()}]The following expressions are invalid: [ A * {B (C D})], [ { ( ] ) ( ) }

Sagot :

Answer:

Explanation:

The following code is written in Java. It uses for loops to loop through the array of characters, and uses IF statements to check if the symbols in the expression are balanced. If so it returns true, otherwise it breaks the function and returns false. Two test cases have been provided in the main method and the output can be seen in the attached image below.

import java.util.ArrayList;

class Brainly {

   public static void main(String[] args) {

       char[] exp = { '[', 'A', '*', '{', 'B', '(', 'C', 'D', ')', '}', ']'};

       char[] exp2 = {'[', 'A', '*', '(', 'C', '}', ']'};

       System.out.println(checkBalance(exp));

       System.out.println(checkBalance(exp2));

   }

   public static boolean checkBalance(char exp[]) {

       ArrayList<Character> symbols = new ArrayList<>();

       for (char x: exp) {

           if ((x =='[') || (x == '{') || (x == '(')) {

               symbols.add(x);

           }

           if (x ==']') {

               if (symbols.get(symbols.size()-1) == '[') {

                   symbols.remove(symbols.size()-1);

               } else {

                   return false;

               }

           }

           if (x =='}') {

               if (symbols.get(symbols.size()-1) == '{') {

                   symbols.remove(symbols.size()-1);

               } else {

                   return false;

               }

           }

           if (x ==')') {

               if (symbols.get(symbols.size()-1) == '(') {

                   symbols.remove(symbols.size()-1);

               } else {

                   return false;

               }

           }

       }

       return true;

   }

}

View image sandlee09