Parenthesis verification using stack
Source Code in c++:
#include <iostream>
#include <stack>
#include <string>
//Check if left and right parenthesis are matching
bool isValidParenthesis(char first,char second)
{
bool result = false;
if(second == ')' && first == '(')
result = true;
else if (second == '}' && first == '{')
result = true;
else if(second == ']' && first == '[')
result = true;
return result;
}
bool isValidExpression(const std::string& inputString)
{
std::stack<char> parenthesisStack ;
bool isValid = true;
char charToCheck;
for(int i=0;i<inputString.size();++i)
{
if(inputString[i] == '(' || inputString[i] == '{'|| inputString[i] == '[')
{
parenthesisStack.push(inputString[i]);
}
else if(inputString[i] == ')' || inputString[i] == '}'|| inputString[i] == ']')
{
if(parenthesisStack.empty())
{
isValid = false;
break;
}
else
{
charToCheck = parenthesisStack.top();
parenthesisStack.pop();
if(!isValidParenthesis(charToCheck,inputString[i]))
{
isValid = false;
break;
}
}//Enf else
}//End else if
} //End For
if(!parenthesisStack.empty())
isValid = false;
return isValid;
}
int main(void)
{
char input[255];
bool isValidExpr;
std::cout<<"\n Enter String : "<<std::endl;
std::cin.getline(input,255);
isValidExpr = isValidExpression(std::string(input));
if(isValidExpr)
std::cout<<"\n Expression is valid ";
else
std::cout<<"\n Expression is invalid ";
std::system("pause");
}