Explain the application of stack to check the validity of parenthesis in the expression with one example. Also write the pseudocode for the same.

Example: bracket balancing c++

/*
PARENTHESE MATCHING
AUTHOR: UTKARSH SINHA
*/
bool correct_paranthesis(string str){
	stack<char> stk;
	map<char,char> bracket_map;
	bracket_map[')'] = '(';
	bracket_map['}'] = '{';
	bracket_map[']'] = '[';
	
	for(int i=0; i<str.size(); i++){
		if(str[i] == '(' || str[i] == '{' || str[i] == '[')
			stk.push(str[i]);
		if(str[i] == ')' || str[i] == '}' || str[i] == ']'){
			if(stk.empty())
				return false;
			if(stk.top() == bracket_map[str[i]] )
				stk.pop();
		}
	}
	
	return (stk.empty() == true);
}

Tags:

Cpp Example