From 25f79209b897a1cd29dde8e5e3ad820d507dc890 Mon Sep 17 00:00:00 2001 From: Tanisha Bansal <145993687+TanishaBansal101@users.noreply.github.com> Date: Tue, 8 Oct 2024 00:09:43 +0530 Subject: [PATCH] Update balanced_brackets.cpp Use Descriptive Variable Names: Change i to currentChar for clarity. Add Comments: Include comments to explain key parts of the code, especially the logic behind the balance checking. Improve Logic Flow: Make the logic easier to follow by clearly separating cases. --- october_2024/balanced_brackets.cpp | 36 +++++++++++++++++------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/october_2024/balanced_brackets.cpp b/october_2024/balanced_brackets.cpp index 8ec430b..93d470f 100644 --- a/october_2024/balanced_brackets.cpp +++ b/october_2024/balanced_brackets.cpp @@ -1,31 +1,37 @@ #include using namespace std; -unordered_map bracket = {{'(', 1}, {'{', 2}, {'[', 3}, {')', -1}, {'}', -2}, {']', -3}}; +// Map to associate brackets with their respective values +unordered_map bracket = { + {'(', 1}, {'{', 2}, {'[', 3}, + {')', -1}, {'}', -2}, {']', -3} +}; + +// Function to check if the brackets in the string are balanced string isBalanced(string s) { - stack st; - for(char i:s){ - if(bracket[i] > 0) { - st.push(i); + stack st; // Stack to keep track of opening brackets + for(char currentChar : s){ // Use a descriptive name for the loop variable + if(bracket[currentChar] > 0) { + st.push(currentChar); // Push opening brackets onto the stack } else { - if(st.empty()) return "NO"; + if(st.empty()) return "NO"; // No matching opening bracket char top = st.top(); st.pop(); - if(bracket[top] + bracket[i] != 0) { - return "NO"; + // Check if the brackets match + if(bracket[top] + bracket[currentChar] != 0) { + return "NO"; // Mismatched brackets } } } - if(st.empty()) return "YES"; - return "NO"; + return st.empty() ? "YES" : "NO"; // Return YES if all brackets matched } int main() { int t; - cin >> t; - while(t--) { + cin >> t; // Read number of test cases + while(t--) { string s; - cin >> s; - cout << isBalanced(s) << endl; + cin >> s; // Read the string of brackets + cout << isBalanced(s) << endl; // Output the result } -} \ No newline at end of file +}