In: Computer Science
In java please Question: You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts:
`Hey,
Note: If you have any queries related to the answer please do comment. I would be very happy to resolve all your queries.
import java.util.ArrayList; // import the ArrayList class
public class Test{
public static int countWaysToSplit(String s,ArrayList<String>
strs)
{
if(strs.size()>=3&&s.length()!=0)
return 0;
if(s.length()==0)
{
if(strs.size()<3)
return 0;
String a=strs.get(0);
String b=strs.get(1);
String c=strs.get(2);
String s1=a+b;
String s2=b+c;
String s3=c+a;
if(!s1.equals(s2)&&!s2.equals(s3)&&!s3.equals(s1))
{
return 1;
}
else
return 0;
}
int sum=0;
for(int i=0;i<s.length();i++)
{
strs.add(s.substring(0,i+1));
sum+=countWaysToSplit(s.substring(i+1,s.length()),strs);
strs.remove(strs.size()-1);
}
return sum;
}
public static void main(String []args){
String s = "xzxzx";
ArrayList<String> strs = new ArrayList<String>();
System.out.println(countWaysToSplit(s,strs));
}
}
Kindly revert for any queries
Thanks.