diff --git a/balanced_parenthesis.cpp b/balanced_parenthesis.cpp new file mode 100644 index 0000000..118d942 --- /dev/null +++ b/balanced_parenthesis.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +bool isValid(string s) +{ + int n = s.size(); + stack st; + bool ans = true; + for (int i = 0; i < n; i++) + { + if (s[i] == '{' or s[i] == '(' or s[i] == '[') + { + st.push(s[i]); + } + else if (s[i] == ')') + { + if (!st.empty() and st.top() == '(') + { + st.pop(); + } + else + { + ans = false; + break; + } + } + else if (s[i] == ']') + { + if (!st.empty() and st.top() == '[') + { + st.pop(); + } + else + { + ans = false; + break; + } + } + else if (s[i] == '}') + { + if (!st.empty() and st.top() == '{') + { + st.pop(); + } + else + { + ans = false; + break; + } + } + } + if(!st.empty()){ + return false; + } + return ans; +} +int main() +{ + string s = "{([])}"; + + if(isValid(s)){ + cout<<"valid string "; + } + else{ + cout<<"invalid string "; + } + return 0; +}