Java Program to Check if a String is a Valid Shuffle of Two Distinct Strings

In the following example of Java program to check if a string is a valid shuffle of two distinct strings :
Program :
public class ValidShuffleDemo {
    public static boolean isValidShuffle(String str, String s1, String s2) {
        if (str.length() != s1.length() + s2.length()) {
            return false;
        }

        int i = 0, j = 0, k = 0;
        while (k < str.length()) {
            if (i < s1.length() && str.charAt(k) == s1.charAt(i)) {
                i++;
            } else if (j < s2.length() && str.charAt(k) == s2.charAt(j)) {
                j++;
            } else {
                return false;
            }
            k++;
        }

        return true;
    }

    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "def";
        String str1 = "adbecf";
        String str2 = "abcdefg";

        if (isValidShuffle(str1, s1, s2)) {
            System.out.println(str1 + " is a valid shuffle of " + s1 + " and " + s2);
        } else {
            System.out.println(str1 + " is not a valid shuffle of " + s1 + " and " + s2);
        }

        if (isValidShuffle(str2, s1, s2)) {
            System.out.println(str2 + " is a valid shuffle of " + s1 + " and " + s2);
        } else {
            System.out.println(str2 + " is not a valid shuffle of " + s1 + " and " + s2);
        }
    }
}
Output :
adbecf is a valid shuffle of abc and def
abcdefg is not a valid shuffle of abc and def
In this program, the isValidShuffle() method takes three arguments: str, s1, and s2. It first checks if the length of str is equal to the sum of the lengths of s1 and s2. If not, it returns false.

The method then initializes three variables i, j, and k to 0, which will be used to traverse s1, s2, and str, respectively. It then uses a while loop to iterate through str character by character. If the current character in str matches the next character in s1, i is incremented. If the current character in str matches the next character in s2, j is incremented. If the current character in str does not match either the next character in s1 or s2, the method returns false. Finally, if the loop completes without returning false, the method returns true.

In the main() method, we test the isValidShuffle() method with two input strings: str1, which is a valid shuffle of s1 and s2, and str2, which is not. The program outputs the result of each test using System.out.println().