Task is to check if given string contains balanced sets of {}
, []
and ()
.
For example, check(\"{[}]\")
must return
You can check the matching brackets by following simple piece of code.
int bracketMatcher(string s)
{
list *countsList = new list();
string expression = s;
int correctBrackets = 1;
for (int index = 0; index < expression.size(); index++) {
char ch = expression[index];
if (ch == '(')
{
countsList->push_back(index);
}
else if (ch == ')')
{
if (countsList->size() == 0)
{
correctBrackets = 0;
break;
}
countsList->pop_back();
}
}
if (countsList->size() != 0)
{
correctBrackets = 0;
}
return correctBrackets;
}
or if you want to find a specific bracket type then can also use following function.
bool bracketMatcher(string s , char c)
{
list *countsList = new list();
string expression = s;
bool correctBrackets = true;
char secondCh =' ';
switch (c) {
case '(': // open parenthesis
secondCh = ')';
break;
case '<': // open angle
secondCh = '>';
break;
case '[': // open bracket
secondCh = ']';
break;
case '{': // open brace
secondCh = '}';
break;
default:
break;
}
for (int index = 0; index < expression.size(); index++) {
char ch = expression[index];
if (ch == c)
{
countsList->push_back(index);
}
else if (ch == secondCh)
{
if (countsList->size() == 0)
{
correctBrackets = false;
break;
}
countsList->pop_back();
}
}
if (countsList->size() != 0)
{
correctBrackets = false;
}
return correctBrackets;
}
int main() {
string s = " ((hello ) (()) llll {}word (aad))";
//always specify the opening bracket here
bool parenthesisMatch = bracketMatcher(s,'(');
bool angleBracketsMatch = bracketMatcher(s,'<');
bool bracketMatch = bracketMatcher(s,'[');
bool bracesMatch = bracketMatcher(s, '{');
if(parenthesisMatch && angleBracketsMatch && bracketMatch && bracesMatch) {
cout << "found all matching brackets" << endl;
}
else{
cout << "could not find all matching brackets" << endl;
}
return 0;
}