program to find balanced parentheses code example

Example 1: 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);
}

Example 2: Algorithm check balanced parentheses

if (null == str || ((str.length() % 2) != 0)) {
    return false;
} else {
    char[] ch = str.toCharArray();
    for (char c : ch) {
        if (!(c == '{' || c == '[' || c == '(' || c == '}' || c == ']' || c == ')')) {
            return false;
        }
    }
}

Tags:

Java Example