22.3k views
0 votes
Can someone solve the following problem in C++

Write a function named checkBalance that accepts a string of source code and uses a stack to check whether the braces/parentheses are balanced. Every ( or { must be closed by a } or ) in the opposite order. Return the index at which an imbalance occurs, or -1 if the string is balanced. If any ( or { are never closed, return the string's length.

1 Answer

1 vote

Final answer:

A C++ function called checkBalance uses a stack to match opening and closing braces/parentheses in a string and returns the index at which an imbalance occurs or -1 if balanced.

Step-by-step explanation:

The function checkBalance in C++ can be implemented using a stack to track the opening and closing of parentheses or braces. If an opening brace or parenthesis is encountered, it is pushed onto the stack. When a closing brace or parenthesis is seen, the stack is popped and we check for a matching pair. If an imbalance is detected at any point, or if there are remaining elements in the stack after processing the entire string, we can determine the index of the imbalance or return the length of the string, respectively.

Example in C++:

int checkBalance(const std::string& code) {
std::stack<char> s;
for (int i = 0; i < code.length(); ++i) {
if (code[i] == '(' || code[i] == '') {
if (s.empty() || (s.top() == '(' && code[i] != ')') || (s.top() == '{' && code[i] != '}')) return i;
s.pop();
}
}
return s.empty() ? -1 : code.length();
}

User Abdelaziz Elrashed
by
7.7k points