Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. #include <string>
  2. #include <map>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. // !!!
  8. // Write a function Validate that will validate the brackets balance.
  9. // A bracket is considered to be any one of the following characters: (){}[].
  10. // Two brackets are considered to be a matched pair if the an opening bracket (, [, {
  11. // occurs to the left of a closing bracket ), ], } of the exact same type.
  12. // There are three types of matched pairs of brackets: [], {}, and ().
  13. // A matching pair of brackets is not balanced if the set of brackets it encloses are not matched.
  14. // For example, {[(])} is not balanced because the contents in between { and } are not balanced.
  15. // Function must return true if the brackets a balanced and false, if not.
  16.  
  17. bool Validate(const string& expression)
  18. {
  19. //std::cout << "11111" << std::endl;
  20. if(expression.size() % 2 != 0)
  21. return false;
  22.  
  23. //std::cout << "22222222222" << std::endl;
  24. if(expression.empty())
  25. return true;
  26.  
  27. //std::cout << expression[0] << expression[expression.size()-1] << std::endl;
  28. if(
  29. !(expression[0] == '[' && expression[expression.size()-1] == ']')
  30. && !(expression[0] == '(' && expression[expression.size()-1] == ')')
  31. && !(expression[0] == '{' && expression[expression.size()-1] == '}')
  32.  
  33. )
  34. return false;
  35.  
  36. if(
  37. !((expression[0] == '[' && expression[expression.size()-1] == ']')
  38. || (expression[0] == '(' && expression[expression.size()-1] == ')')
  39. || (expression[0] == '{' && expression[expression.size()-1] == '}'))
  40.  
  41. )
  42. return false;
  43.  
  44.  
  45. string new_expression = expression.substr(1,expression.size()-2);
  46.  
  47. return Validate(new_expression);
  48. }
  49.  
  50. void Assert(bool cond, const string& message)
  51. {
  52. if (!cond) {
  53. printf(message.c_str());
  54. printf("\n");
  55. }
  56. }
  57.  
  58. int main()
  59. {
  60. Assert(Validate("{") == false, "Open bracket has not closing bracket, must not be valid");
  61. Assert(Validate("{[(])}") == false, "The expression is not balanced, must not be valid");
  62. Assert(Validate("") == true, "Empty expression must be valid");
  63. Assert(Validate("[()]") == true, "The expression is balanced, must be valid");
  64. Assert(Validate("{{[[(())]]}}") == true, "The expression is balanced, must be valid");
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement