简体   繁体   中英

Why does this recursive method work?

I am writing a function to fulfill these requirements: 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

The correct solution shown on the site is:

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;
}

I don't understand why this works. If the given string has a character other than ( like a " , won't it hit the else case and return false rather than skipping to the next ( ?

This will definitely not work if the input string contain some thing other than ( and ) to make this work just call another function like below before calling this function:

clean(String str){
    String str = "(((X+y)+z))";
    String retStr = "";
    for(int i = 0 ; i<str.length() ; i++){
        if(str.charAt(i) == '(' || str.charAt(i) == ')')
        {
            retStr += str.charAt(i);
        }
    }
    return retStr
}

and then call your recursive function with input of retStr .

As seems typical with much example code, the suggested correct solution is inadiquate.

Here is an actually correct solution:

public boolean nestParen(final String value)
{
    if (value != null)
    {
        if (value.isEmpty())
        {
            return true;
        }

        if (value.charAt(0) == '(' && value.charAt(value.length()-1) == ')')
        {
            return nestParen(value.substring(1, value.length()-1));
        }
        else
        {
           return false;
        }
    }
    else // value is null
    {
        return true;
    }
}

Explanation: (same as with the other answer)

  1. if the parameter is not null, continue. This prevents NullPointerExceptions.
  2. if the parameter is empty, return true. The problem appears to be return true if a string contains zero or more nested pairs of parens and nothing else.
  3. If the first char is '(' and the last char is ')', strip these chars and check again (this is the recursion).
  4. otherwise (first is not '(' and/or last is not ')') return false.
  5. lastly, if the parameter was null, return true (it contains zero pairs and nothing else).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM