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.
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;
}
}
We hope you found this helpful. Feel free to come back anytime for more accurate answers and updated information. We appreciate your visit. Our platform is always here to offer accurate and reliable answers. Return anytime. We're here to help at Westonci.ca. Keep visiting for the best answers to your questions.