Recursion Doubt with String in Java

2

I'm trying to solve the following exercise:

  

An S collection of strings is defined recursively 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 say which of the following strings belong to S:

     

(a) to

     

(b) ab

     

(c) flap

     

(d) aaab

     

(e) bbbbb

My code looks like this:

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

In the last return is where I can not solve, I know that in theory it should be something like this:

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

But I can not, could anyone help me?

    
asked by anonymous 25.08.2018 / 17:33

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 it still lacks a condition to work because you have to make sure that there is at least one character in the string. This is possible with a if (str.isEmpty()) return false; . You can also take advantage of this if and check if the string is null .

The code looks 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));
}
    
25.08.2018 / 19:23