w3resource

Java: Find all interleavings of specified strings


33. All Interleavings of Strings

Write a Java program to find all interleavings of given strings.

Sample Solution:

Java Code:

// Import necessary Java utilities.
import java.util.HashSet;
import java.util.Set;

// Define a class named Main.
class Main {
    
    // Define a method to find all interleavings of two strings.
    public static void allInterleavings(String res, String P, String Q, Set out) {
        // If both strings are empty, add the result to the output set.
        if (P.length() == 0 && Q.length() == 0) {
            out.add(res);
            return;
        }
        
        // If string P is not empty, recursively call allInterleavings with the first character of P removed.
        if (P.length() > 0) {
            allInterleavings(res + P.charAt(0), P.substring(1), Q, out);
        }
        
        // If string Q is not empty, recursively call allInterleavings with the first character of Q removed.
        if (Q.length() > 0) {
            allInterleavings(res + Q.charAt(0), P, Q.substring(1), out);
        }
    }

    // The main method to execute the code.
    public static void main(String[] args) {
        // Define the input strings.
        String P = "WX";
        String Q = "YZ";

        // Print the given strings.
        System.out.println("The given strings are: " + P + "  " + Q);
        System.out.println("The interleavings strings are: ");

        // Create a HashSet to store unique interleavings.
        Set<String> out = new HashSet<>();

        // Call the allInterleavings method to generate interleavings of the input strings.
        allInterleavings("", P, Q, out);

        // Print all the generated interleavings using streams.
        out.stream().forEach(System.out::println);
    }
}

Sample Output:

The given strings are: WX  YZ
The interleavings strings are: 
YWZX
WYZX
YWXZ
WXYZ
YZWX
WYXZ

Flowchart:

Flowchart: Java String Exercises - Find all interleavings of specified strings



For more Practice: Solve these Related Problems:

  • Write a Java program to generate all interleavings of two strings and then filter out the ones that are palindromes.
  • Write a Java program to interleave two strings and display only those results that start with a vowel.
  • Write a Java program to print all unique interleavings of two strings with different lengths.
  • Write a Java program to generate interleavings of two strings and then sort them in lexicographical order.

Go to:


PREV : Longest Palindromic Substring.
NEXT : Second Most Frequent Character.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.