Guest User

Untitled

a guest
Nov 17th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. //Problem solution using the stack data structure
  2. #include <iostream>
  3. #include <string>
  4. #include <stack>
  5. using namespace std;
  6.  
  7. bool match(char o, char c){ //match function it verifies if the open (o) match the closing (c)
  8. if((o=='(' && c==')') ||
  9. (o=='[' && c==']') ||
  10. (o=='{' && c=='}')){
  11. return true;
  12. }
  13. else return false;
  14. }
  15. int main(){
  16. bool bal=true; //we consider the string balanced by default
  17. string s="(kljfsq()([)]()()(jqs)fkl;f,sndf)";
  18. stack<char> ss; //We create the stack
  19. for (size_t i = 0; i < s.length(); i++) { //Going through the string
  20. if (s[i]=='('|| s[i]=='[' || s[i]=='{') { // if s[i] is a opening parenthesis or a bracket or a brace
  21. ss.push(s[i]); // we push it at the top of the stack
  22. }
  23. else if(s[i]==')'|| s[i]==']' || s[i]=='}'){ // if s[i] is a closing parenthesis or a bracket or a brace
  24. if (!ss.empty() && match(ss.top(),s[i])) { //if the stack is not empty and the top of it match s[i]
  25. ss.pop(); //we pop from the top of the stack
  26. }
  27. else{ //if the stack is empty or the top pf it does not match s[i]
  28. bal=false; //The string is not balanced (bal=false)
  29. break;
  30. }
  31. }
  32. }
  33. if(!ss.empty()) bal=false; //after all if the stack is not empty the string is not balanced (bal=false)
  34. if(bal) cout << "Balanced" << endl; //if bal is true then we print balanced
  35. else cout << "Not Balanced" << endl; //else we print not balanced
  36. return 0;
  37. }
Add Comment
Please, Sign In to add comment