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);
}
}
}
adbecf is a valid shuffle of abc and def
abcdefg is not a valid shuffle of abc and def
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
.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
.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()
.