Java program to check if a string is a valid shuffle of two distinct strings
Here's an example Java program to check if a string is a valid shuffle of two distinct strings:
public class StringShuffleChecker { public static void main(String[] args) { String str1 = "abc"; String str2 = "def"; String shuffle = "adbecf"; if (isShuffle(str1, str2, shuffle)) { System.out.println(shuffle + " is a valid shuffle of " + str1 + " and " + str2); } else { System.out.println(shuffle + " is not a valid shuffle of " + str1 + " and " + str2); } } public static boolean isShuffle(String str1, String str2, String shuffle) { if (str1.length() + str2.length() != shuffle.length()) { return false; } int i = 0, j = 0, k = 0; while (k < shuffle.length()) { if (i < str1.length() && str1.charAt(i) == shuffle.charAt(k)) { i++; } else if (j < str2.length() && str2.charAt(j) == shuffle.charAt(k)) { j++; } else { return false; } k++; } return true; } }
This program uses an isShuffle
method that takes three strings as input: str1
, str2
, and shuffle
. The method returns true
if shuffle
is a valid shuffle of str1
and str2
, and false
otherwise.
To check if shuffle
is a valid shuffle of str1
and str2
, the isShuffle
method first checks if the length of shuffle
is equal to the sum of the lengths of str1
and str2
. If not, the method returns false
, indicating that shuffle
cannot be a valid shuffle of str1
and str2
.
The method then uses three pointers: i
for str1
, j
for str2
, and k
for shuffle
. It loops through each character of shuffle
and checks if the character at k
matches the character at either i
or j
. If the character matches the character at i
, the method increments i
. If the character matches the character at j
, the method increments j
. If the character does not match either i
or j
, the method returns false
, indicating that shuffle
cannot be a valid shuffle of str1
and str2
.
If the method reaches the end of shuffle
without finding any mismatches, it returns true
, indicating that shuffle
is a valid shuffle of str1
and str2
.
In the main method, the isShuffle
method is called with three strings: str1
contains the characters "abc"
, str2
contains the characters "def"
, and shuffle
contains the characters "adbecf"
. If shuffle
is a valid shuffle of str1
and str2
, the program prints a message indicating that shuffle
is a valid shuffle of str1
and str2
. Otherwise, it prints a message indicating that shuffle
is not a valid shuffle of str1
and str2
.