#include <iostream> #include <stack> #include <string> #include <unordered_map> using namespace std; string isBalanced(string s) { // Mapping of closing brackets to their corresponding opening brackets unordered_map<char, char> bracketMap = { {')', '('}, {']', '['}, {'}', '{'} }; stack<char> stk; for (char ch : s) { // If it's an opening bracket, push it onto the stack if (bracketMap.find(ch) == bracketMap.end()) { stk.push(ch); } // If it's a closing bracket else { // Check if the stack is empty or the top of the stack doesn't match if (stk.empty() || stk.top() != bracketMap[ch]) { return "NO"; } // Pop the matching opening bracket stk.pop(); } } // If the stack is empty, all brackets matched correctly return stk.empty() ? "YES" : "NO"; } int main() { int n; cin >> n; // Read the number of strings cin.ignore(); // Ignore the newline after the number input for (int i = 0; i < n; ++i) { string s; getline(cin, s); // Read each bracket string cout << isBalanced(s) << endl; // Output YES or NO } return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter