Recursion Doubt with String in Java

Asked

Viewed 134 times

2

I’m trying to solve the following exercise:

A string collection S is recursively defined by:

  • 'a' and 'b' belong to S;
  • if X belongs to S, then Xb also belongs to S;

Write a procedure that implements this definition recursively and tell which of the following strings belong to S:

(a) to

(b) ab

(c) tab

(d) aaab

(e) bbbbb

My code is as follows:

    static boolean funcao(String str){
        if(str.equals("a") || str.equals("b"))
             return true;
        return(...)

At last return is where I can’t solve, I know in theory he should be more or less like this:

   retorna(str[ultimo caracter] == 'b' && funcao(str[do primeiro ao penúltimo caractere]);

But I’m not getting it, someone would know to help me?

1 answer

2


str[ultimo caracter]
str.charAt(str.length() - 1)
str[do primeiro ao penúltimo caractere]
str.substring(0, str.length() - 1)

But there is still one condition to work, as you have to ensure that there is at least one character in the string. This is possible with a if (str.isEmpty()) return false;. You can also enjoy this if and check if the string is null.

The code goes like this:

private static boolean funcao(String str) {
    if (str == null || str.isEmpty()) return false;
    if (str.equals("a") || str.equals("b")) return true;
    return str.charAt(str.length() - 1) == 'b'
            && funcao(str.substring(0, str.length() - 1));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.