Code:
//valid : ([(a+b)+c]) + x
//invalid : ([(a+b+c]) + x
#include <iostream>
#include <stack>
#include <string>
using namespace std;
//function declarations
bool Is_Bracket_Open(char);
bool Is_Bracket_Closed(char);
bool Check_Match(char,char);
bool Is_Valid(string);
int main()
{
string A ="([(a+b)+c])+x";
string B ="([(a+b+c)+x";
if(Is_Valid(A)==true)
{
cout<<"Valid";
}
else
cout<<"***ERR";
cin.get();
cin.get();
}
/*=============================================
Given: my_string a string
Task: To determine if the brackets are valid
return: Nada
============================================*/
bool Is_Valid(string my_string)
{
stack<char> my_stack;//create a stack of chars
for(int i=0; i<my_string.length(); i++)//iterate through string
{
char Symbol;
Symbol = my_string[i];
if(Is_Bracket_Open(Symbol)==true)
{
//push open bracket onto stack
my_stack.push(Symbol);
}
if(Is_Bracket_Closed(Symbol)==true)
{
char top;
if (!my_stack.empty())
{
top = my_stack.top();
if(Check_Match(top,Symbol)==true)
{
//discard opening bracket
my_stack.pop();
}
else
{
return false;
break;
}
}
else
{
return false;
break;
}
}
}
if(!my_stack.empty())
{
return false;
}
else
{
return true;
}
}
bool Is_Bracket_Open(char ch)
{
if ((ch == '(')||
(ch == '[')||
(ch == '{'))
return true;
else
return false;
}
bool Is_Bracket_Closed(char ch)
{
if ((ch == ')')||
(ch == ']')||
(ch == '}'))
return true;
else
return false;
}
bool Check_Match(char A,char B)
{
if ((A=='(')&&(B==')') )
{
return true;
}
else if ((A=='{')&&(B=='}') )
{
return true;
}
else if ((A=='[')&&(B==']') )
{
return true;
}
}
That's an example using the stack... it may or maynot be helpful