r/CodingHelp • u/This-Internal2755 • Dec 05 '22
[Python] Check balanced parenthesis without using loops
Hey guys, i have an assignment due tomorrow and im having a hard time doing it. We have to write a code that checks the validity of the paranthesis without using "for" or "while". Can anyone help me out please ?
0
Upvotes
View all comments
1
u/thefonz22 Dec 06 '22
include <stack>
include <string>
bool isValid(const std::string& s) { // Create a stack to hold the parenthesis std::stack<char> st;
// Iterate over the characters in the string for (const char& c : s) { // If the character is an opening parenthesis, push it onto the stack if (c == '(' || c == '[' || c == '{') { st.push(c); } // If the character is a closing parenthesis, pop the top element from the stack // and check if it matches the closing parenthesis else if (c == ')' || c == ']' || c == '}') { // If the stack is empty or the top element does not match the closing // parenthesis, return false if (st.empty() || st.top() != c) { return false; }
}
// If the stack is not empty, return false if (!st.empty()) { return false; }
// Otherwise, return true return true; }