Monday, September 24, 2012

Check if a string has balanced parenthesis

1 comment:

  1. int par = 0;
    for(int i = 0; i < str.length; i++) { // str != null
    char ch = str.charAt(i);
    if (ch == '(') par++;
    if (ch == ')') par--;
    if (par < 0) return false;
    }

    It seems suspiciously simple. Am I missing something?

    ReplyDelete