check for 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: bracket balanced or not in python

def isBalanced(final_str):
    type_brackets = ['()', '{}', '[]']
    while any(x in final_str for x in type_brackets):
        for br in type_brackets:
            final_str = final_str.replace(br, '')
    return not final_str


string = "{[]{()}}"
print(string, "-", "Balanced"
      if isBalanced(string) else "Unbalanced")

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

Example 4: PYTHON STACK FUNCTION count the valid number of brackets Returns the total number of valid brackets in the string

import sys

def error(c, line_number, column_number):
    print 'Error: unmatched', c, 'line', line_number, 'column', column_number

def check(stack, wanted, c, line_number, column_number):
    if stack[-1] != wanted:
        error(c, line_number, column_number)
    else:
        stack.pop()

def check_parentheses(f):
    stack = list()
    line_number = 0
    for line in f:
        line_number = line_number + 1
        column_number = 0
        for c in line:
            column_number = column_number + 1
            if c == '(' or c == '[' or c == '{':
                stack.append(c)
            elif c == ')':
                check(stack, '(', ')', line_number, column_number)
            elif c == ']':
                check(stack, '[', ']', line_number, column_number)
            elif c == '}':
                check(stack, '{', '}', line_number, column_number)

def main():
    filename = sys.argv[1]
    try:
        f = file(filename)
    except IOError:
        sys.stderr.write('Error: Cannot open file %s' % filename)
        sys.exit(1)
    check_parentheses(f)
    f.close()

main()

Tags:

Java Example