Given 2 strings A and B, print all the interleavings of the 2 strings. An interleaved string of given two strings preserves the order of characters in individual strings and uses all the characters of both the strings. For simplicity, you can assume that the strings have unique characters.
input:
2
nkb gl
bn zh
i wrote some code but im not getting the sorted strings.
public class Test {
static void interleavings(String A, String B, char[] ans, int m, int n, int idx)
{
if(m==0 && n==0)
{
System.out.println(ans);
return;
}
if(m != 0)
{
ans[idx]=A.charAt(0);
interleavings(A.substring(1,m), B, ans, m-1, n, idx+1);
}
if(n != 0)
{
ans[idx]= B.charAt(0);
interleavings(A, B.substring(1,n), ans, m, n-1, idx+1);
}
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int i = 0; i < t; i++)
{
String s1=s.next();
String s2=s.next();
char [] ans = new char[s1.length()+s2.length()];
System.out.println("Case #"+(i+1)+":");
interleavings(s1,s2,ans,s1.length(),s2.length(),0);
}
}
}
My output
Case #1:
nkbgl
nkgbl
nkglb
ngkbl
ngklb
nglkb
gnkbl
gnklb
gnlkb
glnkb
Case #2:
bnzh
bznh
bzhn
zbnh
zbhn
zhbn
Expected output
Case #1:
glnkb
gnkbl
gnklb
gnlkb
ngkbl
ngklb
nglkb
nkbgl
nkgbl
nkglb
Case #2:
bnzh
bzhn
bznh
zbhn
zbnh
zhbn
I'm new to java can someone please guide me. how to over come this problem please.