Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <map>
- #include <iostream>
- using namespace std;
- // !!!
- // Write a function Validate that will validate the brackets balance.
- // A bracket is considered to be any one of the following characters: (){}[].
- // Two brackets are considered to be a matched pair if the an opening bracket (, [, {
- // occurs to the left of a closing bracket ), ], } of the exact same type.
- // There are three types of matched pairs of brackets: [], {}, and ().
- // A matching pair of brackets is not balanced if the set of brackets it encloses are not matched.
- // For example, {[(])} is not balanced because the contents in between { and } are not balanced.
- // Function must return true if the brackets a balanced and false, if not.
- bool Validate(const string& expression)
- {
- //std::cout << "11111" << std::endl;
- if(expression.size() % 2 != 0)
- return false;
- //std::cout << "22222222222" << std::endl;
- if(expression.empty())
- return true;
- //std::cout << expression[0] << expression[expression.size()-1] << std::endl;
- if(
- !(expression[0] == '[' && expression[expression.size()-1] == ']')
- && !(expression[0] == '(' && expression[expression.size()-1] == ')')
- && !(expression[0] == '{' && expression[expression.size()-1] == '}')
- )
- return false;
- if(
- !((expression[0] == '[' && expression[expression.size()-1] == ']')
- || (expression[0] == '(' && expression[expression.size()-1] == ')')
- || (expression[0] == '{' && expression[expression.size()-1] == '}'))
- )
- return false;
- string new_expression = expression.substr(1,expression.size()-2);
- return Validate(new_expression);
- }
- void Assert(bool cond, const string& message)
- {
- if (!cond) {
- printf(message.c_str());
- printf("\n");
- }
- }
- int main()
- {
- Assert(Validate("{") == false, "Open bracket has not closing bracket, must not be valid");
- Assert(Validate("{[(])}") == false, "The expression is not balanced, must not be valid");
- Assert(Validate("") == true, "Empty expression must be valid");
- Assert(Validate("[()]") == true, "The expression is balanced, must be valid");
- Assert(Validate("{{[[(())]]}}") == true, "The expression is balanced, must be valid");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement