Two brackets are considered to be a matched pair if an opening bracket (i.e., (, [, or { ) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets are not matched.
Write a program to determine whether the input sequence of brackets is balanced or not. If a string is balanced, it prints YES on a new line; otherwise, print NO on a new line.
Example:
Input: {[()]} and Output: YES
Input: {[(])} and Output: NO
#include <iostream>
#include <stack>
bool is_balanced(const std::string& pattern) {
std::stack<char> stack;
for (size_t i = 0; i < pattern.size(); i = i + 1) {
switch (pattern[i]) {
case '(': case '[': case '{':
stack.push(pattern[i]);
break;
case ')':
if (!stack.empty() and stack.top() == '(')
stack.pop();
break;
case ']':
if (!stack.empty() and stack.top() == '[')
stack.pop();
break;
case '}':
if (!stack.empty() and stack.top() == '{')
stack.pop();
break;
}
}
return stack.empty();
}
int main() {
while (true) {
std::cout << "Enter new string sequence: ";
std::string pattern;
if (pattern == "quit") return 0;
std::cin >> pattern;
if (is_balanced(pattern)) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
}
}
Comments
Leave a comment