You are given a string S consisting of letters 'a' and 'b'. You want to split it into
three
separate non-empty parts. The lengths of the parts can differ from one another.
In how many ways can you split s into three parts, such that each part contains
the
same number of letters 'a'?
Write a program that accepts a string as a parameter from the command
prompt and
print an integer value as an output in java
Answers
Answered by
27
Answer:
what is the correct answer
Answered by
13
Answer:
I have c++ solution for the question.
// you can use includes, for example:
#include <algorithm>
int solution(string &S) {
int As = count(S.begin(), S.end(), 'a');
if(As==0) return (int)((S.length()-1)*(S.length()-2))/2;
//nCk formula (n-1 C 2) = (n-1)!/(n-3)!*2! = (n-1)(n-2)/2
if(As%3!=0) return 0;
int count=0;
int possibleAs = As/3;
int first=0;
int second=0;
for(unsigned int i=0;i<S.length();i++){
if(S[i]=='a') count+=1;
if(count==possibleAs) first+=1;
else if(count==2*possibleAs) second+=1;
}
return (int)(first*second);
Explanation:
Similar questions