Exercise on recursive methods:
Use the technique divide-and-conquer to write a Java method
int findBBA(char[] array, int left, int right) that returns the frequency of the
string ‘‘BBA’’ in the array spanning from left to right.
Hi everyone, I’ve managed to solve this kind of problem only when the sequence
was two characters/digits long (for example the number of occurrences of “01” in
an array of integers or “BA” in one of characters).
I’ve done some research but I can’t find a solution for this problem. Could anyone help please?
Thank you very much.
public static int _findBBA(char[] a, int l, int r) {
if(l+2 >= r)
return 0;
int mid = (l+r)/2;
int find1 = _findBBA(a, l, mid);
int find2 = _findBBA(a, mid, r);
int res = find1 + find2;
if(a.length % 2 == 0) {
if(a[mid-1] == 'B' && a[mid] == 'B' && a[mid+1] == 'A')
res++;
if(a[mid-2] == 'B' && a[mid-1] == 'B' && a[mid] == 'A')
res++;
}
else
if(a[mid-1] == 'B' && a[mid] == 'B' && a[mid+1] == 'A')
res++;
return res;
}
Francesco Pandolfo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.