From 8cb86de0d7d13e26be6ae1bb522a393e8e687de2 Mon Sep 17 00:00:00 2001 From: Ritwik Vaidya <61344435+ritwik4690@users.noreply.github.com> Date: Mon, 22 Feb 2021 07:03:58 +0530 Subject: [PATCH] Add stacks for c-or-cpp (#80) --- stacks/README.md | 5 +++ stacks/c-or-cpp/balanced-paranthesis.cpp | 43 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 stacks/README.md create mode 100644 stacks/c-or-cpp/balanced-paranthesis.cpp diff --git a/stacks/README.md b/stacks/README.md new file mode 100644 index 00000000..5f4c154f --- /dev/null +++ b/stacks/README.md @@ -0,0 +1,5 @@ +# Stacks + +### C or C++ + +1. [Balanced Paranthesis](c-or-cpp/balanced-paranthesis.cpp) diff --git a/stacks/c-or-cpp/balanced-paranthesis.cpp b/stacks/c-or-cpp/balanced-paranthesis.cpp new file mode 100644 index 00000000..dc845594 --- /dev/null +++ b/stacks/c-or-cpp/balanced-paranthesis.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; +bool isBalanced(string s) { + stack st; + char ch; + for (int i = 0; i < s.length(); i++) { + if (s[i] == '(' || s[i] == '[' || s[i] == '{') { + st.push(s[i]); + continue; + } + if (st.empty()) + return false; + switch (s[i]) { + case ')': + ch = st.top(); + st.pop(); + if (ch == '{' || ch == '[') + return false; + break; + case '}': + ch = st.top(); + st.pop(); + if (ch == '(' || ch == '[') + return false; + break; + case ']': + ch = st.top(); + st.pop(); + if (ch == '(' || ch == '{') + return false; + break; + } + } + return (st.empty()); +} +int main() { + string input = "{}[({})]"; + if (isBalanced(input)) + cout << "Balanced"; + else + cout << "Not Balanced"; + return 0; +} \ No newline at end of file