employer cover photo
employer logo
employer logo

WhiteHedge Technologies

Est-ce votre entreprise ?

Question d’entretien chez WhiteHedge Technologies

1.Write a Java Program to find out whether the given string is **Balanced Parentheses** or NOT?

Réponse à la question d'entretien

Utilisateur anonyme

26 août 2024

public class BalancedParentheses { public static boolean isBalanced(String str) { // Create a stack to keep track of opening parentheses Stack stack = new Stack<>(); // Loop through each character in the string for (char ch : str.toCharArray()) { // If the character is an opening parenthesis, push it onto the stack if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } // If the character is a closing parenthesis, check for matching opening parenthesis else if (ch == ')' || ch == '}' || ch == ']') { // If the stack is empty or the top of the stack doesn't match, it's unbalanced if (stack.isEmpty() || !isMatchingPair(stack.pop(), ch)) { return false; } } } // If the stack is empty, all parentheses were balanced; otherwise, it's unbalanced return stack.isEmpty(); } // Helper method to check if two characters are matching parentheses private static boolean isMatchingPair(char open, char close) { return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']'); } public static void main(String[] args) { String testStr1 = "({[]})"; String testStr2 = "({[})"; System.out.println("String: " + testStr1 + " is balanced: " + isBalanced(testStr1)); System.out.println("String: " + testStr2 + " is balanced: " + isBalanced(testStr2)); } }