Created
December 13, 2020 00:52
-
-
Save itirkaa/f8e39abfe145682b8af34136bf253eef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stack> | |
bool isBalanced(std::string sequence) { | |
std::stack<char> stk; | |
for (int i = 0; i < sequence.size(); i++) { | |
if (sequence[i] == '[' || sequence[i] == '{' || sequence[i] == '(') | |
stk.push(sequence[i]); | |
else if (sequence[i] == ']' || sequence[i] == '}' || sequence[i] == ')') { | |
if (stk.empty()) return false; | |
if ((sequence[i] == '[' && stk.top() != ']') || | |
(sequence[i] == '{' && stk.top() != '}') || | |
(sequence[i] == '(' && stk.top() != ')')) | |
return false; | |
stk.pop(); | |
} | |
} | |
return stk.empty(); | |
} | |
int main() { | |
std::string sequence{}; | |
std::cout << "Enter your expression: "; | |
std::cin >> sequence; | |
if (isBalanced(sequence)) | |
std::cout << "Sequence is balanced"; | |
else | |
std::cout << "Sequence is not balanced"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment