diff --git a/Cpp/Parentheses_Checker.cpp b/Cpp/Parentheses_Checker.cpp index 9139e47161..dc61dc5174 100644 --- a/Cpp/Parentheses_Checker.cpp +++ b/Cpp/Parentheses_Checker.cpp @@ -1,52 +1,49 @@ // parentheses_checker.cpp -// Compile with: g++ -std=c++17 parentheses_checker.cpp -o parentheses_checker +// A simple program to check whether the parentheses/brackets/braces +// in each input line are balanced. +// Compile: g++ -std=c++17 parentheses_checker.cpp -o parentheses_checker -#include +#include +#include +#include using namespace std; +// Function to check if two brackets are a matching pair bool isMatching(char open, char close) { - return (open == '(' && close == ')') - || (open == '[' && close == ']') - || (open == '{' && close == '}'); + return (open == '(' && close == ')') || + (open == '[' && close == ']') || + (open == '{' && close == '}'); } +// Function that checks if parentheses in a string are balanced bool areParenthesesBalanced(const string &s) { stack st; for (char ch : s) { if (ch == '(' || ch == '[' || ch == '{') { st.push(ch); } else if (ch == ')' || ch == ']' || ch == '}') { - if (st.empty() || !isMatching(st.top(), ch)) { - return false; // closing bracket without matching opening - } + if (st.empty() || !isMatching(st.top(), ch)) + return false; // unmatched closing bracket st.pop(); - } - // ignore other characters + } + // Ignore non-bracket characters } - return st.empty(); // balanced iff nothing left unmatched + return st.empty(); // Balanced if stack is empty at the end } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); - cout << "Enter string to check (single line). Press Ctrl+D/Ctrl+Z to end:\n"; - string line; - // Read whole line (including spaces). For multiple tests, loop or read until EOF. - if (!getline(cin, line)) return 0; - - bool balanced = areParenthesesBalanced(line); - if (balanced) cout << "Balanced\n"; - else cout << "Not Balanced\n"; + cout << "Enter multiple lines to check parentheses balance.\n"; + cout << "Press Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) to finish input.\n\n"; - // Example quick tests (uncomment to run built-in tests) - /* - vector tests = { - "()[]{}", "([{}])", "(]", "([)]", "a + (b - c) * {d / [e + f]}" - }; - for (auto &t : tests) { - cout << t << " -> " << (areParenthesesBalanced(t) ? "Balanced" : "Not Balanced") << '\n'; + string line; + // Read multiple lines until EOF + while (getline(cin, line)) { + bool balanced = areParenthesesBalanced(line); + cout << (balanced ? "Balanced" : "Not Balanced") << '\n'; } - */ + return 0; }