Saturday, January 30, 2016

Check balanced parentheses

Question: Given a string which contains alpha numeric characters with opening and closing parentheses, check whether parenthesis are balanced correctly.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public boolean isBalanceParenthesis(String str){
        int count = 0;
        for(int i=0; i < str.length(); i++) {
            if(str.charAt(i) == '(') {
                count++;
            }
            else if(str.charAt(i) == ')') {
                count--;
            }
            if(count<0){
                return false;
            }
        }
        return count == 0;
    }

No comments:

Post a Comment