+ 1

Why is this code not working if I add an alphabet in parantheses?

#include <iostream> #include <stack> bool is_valid_parenthesis(std::string str) { std::stack<char> st; for (char c: str) { if (c == '(') { st.push(')'); } else if (c == '{') { st.push('}'); } else if (c == '[') { st.push(']'); } else if (!st.empty()) { if (st.top() != c) { return false; } else { st.pop(); } } } return st.empty(); } int main() { std::string str1{"(a)[]{}"}; if (is_valid_parenthesis(str1)) { std::cout << str1 << " has valid parenthesis." << std::endl; } else { std::cout << str1 << " does not have valid parenthesis." << std::endl; } std::string str2{"([)]"}; if (is_valid_parenthesis(str2)) { std::cout << str2 << " has valid parenthesis." << std::endl; } else { std::cout << str2 << " does not have valid parenthesis." << std::endl; } return 0; }

9th Mar 2019, 7:42 AM
Himanshu Digrase
Himanshu Digrase - avatar
1 Respuesta
+ 3
For the alphabets it doesn't have a pair so it's returning false.... Please keep a condition for c is a bracket and ignore all alphanumeric. https://code.sololearn.com/cj6456rjwzx1/?ref=app
14th Mar 2019, 12:36 PM
Sinjini Das
Sinjini Das - avatar