Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different
Example :
Input: str1 = "AB", str2 = "CD"
Output:
ABCD
ACBD
ACDB
CABD
CADB
CDAB
Another variant of interleaving : Check a given string is interleaving of other two strings
http://www.geeksforgeeks.org/archives/17750
Refer : http://www.geeksforgeeks.org/archives/17743
Example :
Input: str1 = "AB", str2 = "CD"
Output:
ABCD
ACBD
ACDB
CABD
CADB
CDAB
public class InterLeavedStrings {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "def";
if (str1 != null && str1.length() != 0 && str2 != null
&& str2.length() != 0) {
getInterLeavedStrings(str1, str2);
getInterLeavedStrings(str2, str1);
} else if (str1 == null || str1.length() == 0) {
System.out.println(str2);
} else {
System.out.println(str1);
}
}
private static void getInterLeavedStrings(String str1, String str2) {
int m = str1.length();
int n = str2.length();
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println(str1.substring(0, i) + str2.substring(0, j)
+ str1.substring(i, m) + str2.substring(j, n));
}
}
}
}
Another variant of interleaving : Check a given string is interleaving of other two strings
http://www.geeksforgeeks.org/archives/17750
Refer : http://www.geeksforgeeks.org/archives/17743
No comments:
Post a Comment