Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Problem solution using the stack data structure
- #include <iostream>
- #include <string>
- #include <stack>
- using namespace std;
- bool match(char o, char c){ //match function it verifies if the open (o) match the closing (c)
- if((o=='(' && c==')') ||
- (o=='[' && c==']') ||
- (o=='{' && c=='}')){
- return true;
- }
- else return false;
- }
- int main(){
- bool bal=true; //we consider the string balanced by default
- string s="(kljfsq()([)]()()(jqs)fkl;f,sndf)";
- stack<char> ss; //We create the stack
- for (size_t i = 0; i < s.length(); i++) { //Going through the string
- if (s[i]=='('|| s[i]=='[' || s[i]=='{') { // if s[i] is a opening parenthesis or a bracket or a brace
- ss.push(s[i]); // we push it at the top of the stack
- }
- else if(s[i]==')'|| s[i]==']' || s[i]=='}'){ // if s[i] is a closing parenthesis or a bracket or a brace
- if (!ss.empty() && match(ss.top(),s[i])) { //if the stack is not empty and the top of it match s[i]
- ss.pop(); //we pop from the top of the stack
- }
- else{ //if the stack is empty or the top pf it does not match s[i]
- bal=false; //The string is not balanced (bal=false)
- break;
- }
- }
- }
- if(!ss.empty()) bal=false; //after all if the stack is not empty the string is not balanced (bal=false)
- if(bal) cout << "Balanced" << endl; //if bal is true then we print balanced
- else cout << "Not Balanced" << endl; //else we print not balanced
- return 0;
- }
Add Comment
Please, Sign In to add comment