Java > Recursion-1 > nestParen (CodingBat Solution)

Problem:

Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like "(())" or "((()))". Suggestion: check the first and last chars, and then recur on what's inside them.

nestParen("(())") → true
nestParen("((()))") → true
nestParen("(((x))") → false


Solution:

public boolean nestParen(String str) {
  if (str.equals("")) return true;
  if (str.charAt(0) == '(' && str.charAt(str.length()-1) == ')')
    return nestParen(str.substring(1,str.length()-1));
  else
    return false;
}


8 comments :

  1. public boolean nestParen(String str) {
    return str.length() == 0 ||
    ('(' == str.charAt(0) && ')' == str.charAt(str.length() - 1))
    && nestParen(str.substring(1, str.length() - 1));
    }

    ReplyDelete
  2. if(str.equals("")) return true;
    if(str.charAt(0)!='(' || str.charAt(str.length()-1)!=')' ) return false;
    else return nestParen(str.substring(1,str.length()-1));

    ReplyDelete
  3. I also added a check so that it would return false immediately if number of symbols is odd:

    if (str.length() % 2 != 0) return false;

    ReplyDelete
  4. if(str.startsWith("(")&&str.endsWith(")")){
    return nestParen(str.substring(1,str.length()-1));
    }
    return str.equals("");
    }

    ReplyDelete
  5. public boolean nestParen(String str) {
    return str.length() == 0
    || str.charAt(0) == '('
    && str.charAt(str.length() - 1) == ')'
    && nestParen(str.substring(1, str.length() - 1));
    }

    ReplyDelete
  6. public boolean nestParen(String str) {
    if(str.startsWith("(")&&str.endsWith(")")){
    return nestParen(str.substring(1,str.length() - 1));
    }
    return str.isEmpty();
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact