231k views
0 votes
C++ Define a function unbalanced brackets that takes in a string and returns the number of unbalanced brackets. In other words, returns the difference of open and closed curly brackets. int unbalanced brackets(string input); Example Enter a string: { }}} Output -2 Explanation 1 open - 3 closed = -2 Enter a string: {{{}{}}{} Output 1 Explanation 5 open - 4 closed = 1

User Jmfolds
by
8.1k points

1 Answer

4 votes

Final answer:

To define a function called unbalanced brackets in C++ that calculates the number of unbalanced brackets in a given string, the function can iterate through the string and keep a count of the number of open and closed curly brackets encountered.

Step-by-step explanation:

To define a function called unbalanced brackets in C++ that calculates the number of unbalanced brackets in a given string, the function can iterate through the string and keep a count of the number of open and closed curly brackets encountered. For every open bracket, the count is incremented, and for every closed bracket, the count is decremented. The final count represents the difference between open and closed brackets, which is the number of unbalanced brackets in the string.

Here is a code example:

#include <string>

int unbalanced_brackets(std::string input) {
int count = 0;

for (char c : input) {
if (c == '{') {
count++;
} else if (c == '}') {
count--;
}
}

return count;
}

For the first example given, '{}}}', the function would return -2 because there are 1 open bracket and 3 closed brackets, resulting in a difference of -2. For the second example, '{{{}}}{}}', the function would return 1 because there are 5 open brackets and 4 closed brackets, resulting in a difference of 1.

User Sunghoon
by
8.1k points