Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to understand the below question. I kind of know what the method is doing, and it returns True. Also, I don't understand the question. I believe the answer is 2, but I don't know why. Below is the method and question.

In the ABBAB language the alphabet has only two letters. A string of letters (including and one-letter strings) is a valid word, if and only if the isValid method returns true for that string. isValid is defined as follows:

 public boolean isValid(String word)
{
 int n = word.length();

 return n < 1 ||
      (isValid(word.substring(0, n-1) && 
           word.charAt(n-1) == 'B') ||
      (isValid(word.substring(0, n-2) &&
           "BA".equals(word.substring(n-2)));
}

How many valid words of length 7 are there in the ABBABA language?

2 3 15 23 34

share|improve this question
1  
Are you in the middle of an exam? –  Jim Garrison Jul 30 '14 at 22:31
    
No I was just studying it from an online multiple choice practice test. @JimGarrison –  SalceCodec Jul 30 '14 at 22:35
1  
break it down: (isValid(word.substring(0, n-1) && word.charAt(n-1) == 'B') says a string is valid if the last letter has to be 'B', and the rest of string is also valid (by applying the recursive definition of valid to the rest of the string. This will tell you valid strings are of the form ******B –  Ben Jul 30 '14 at 22:35
    
Okay Cool I think I understand. Now what about the question they ask at the end? @Ben –  SalceCodec Jul 30 '14 at 22:36
    
See the edit and you tell me. I also didn't complete the analysis for you either –  Ben Jul 30 '14 at 22:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.