用于检查字符串是否是两个不同字符串的有效洗牌的 Java 程序
要理解此示例,您应该具备以下 Java 编程的知识:
示例:检查一个字符串是否是其他两个字符串的有效洗牌
import java.util.Arrays;
public class Test {
// length of result string should be equal to sum of two strings
static boolean checkLength(String first, String second, String result) {
if (first.length() + second.length() != result.length()) {
return false;
}
else {
return true;
}
}
// this method converts the string to char array
// sorts the char array
// convert the char array to string and return it
static String sortString(String str) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
// convert char array back to string
str = String.valueOf(charArray);
return str;
}
// this method compares each character of the result with
// individual characters of the first and second string
static boolean shuffleCheck(String first, String second, String result) {
// sort each string to make comparison easier
first = sortString(first);
second = sortString(second);
result = sortString(result);
// variables to track each character of 3 strings
int i = 0, j = 0, k = 0;
// iterate through all characters of result
while (k != result.length()) {
// check if first character of result matches
// with first character of first string
if (i < first.length() && first.charAt(i) == result.charAt(k))
i++;
// check if first character of result matches
// with the first character of second string
else if (j < second.length() && second.charAt(j) == result.charAt(k))
j++;
// if the character doesn't match
else {
return false;
}
// access next character of result
k++;
}
// after accessing all characters of result
// if either first or second has some characters left
if(i < first.length() || j < second.length()) {
return false;
}
return true;
}
public static void main(String[] args) {
String first = "XY";
String second = "12";
String[] results = {"1XY2", "Y1X2", "Y21XX"};
// call the method to check if result string is
// shuffle of the string first and second
for (String result : results) {
if (checkLength(first, second, result) == true && shuffleCheck(first, second, result) == true) {
System.out.println(result + " is a valid shuffle of " + first + " and " + second);
}
else {
System.out.println(result + " is not a valid shuffle of " + first + " and " + second);
}
}
}
}
输出
1XY2 is a valid shuffle of XY and 12
Y1X2 is a valid shuffle of XY and 12
Y21XX is not a valid shuffle of XY and 12
在上面的例子中,我们有一个名为 results
的字符串数组. 它包含三个字符串:1XY2
, Y1X2
, 和 Y21XX
. 我们正在检查这三个字符串是否是这两个字符串字符串 first
(XY
) 和 second
(12
) 的有效洗牌.
在这里,我们使用了 3 种方法:
-
checkLength()
- 洗牌后的字符串中的字符数应等于两个字符串中字符的总和。因此,此方法检查洗牌后的字符串的长度是否与字符串
first
和second
的长度之和相同。如果长度不相等,则无需调用该
shuffleCheck()
方法。因此,我们使用if
语句判断// inside main method if (checkLength(first, second, result) == true && shuffleCheck(first, second, result) == true)
-
sortString()
- 此方法将字符串转换为char
数组,然后使用该Arrays.sort()
方法对数组进行排序。最后,返回排序后的字符串。由于我们将洗牌后的字符串与其他两个字符串进行比较,因此对所有三个字符串进行排序将使比较更有效率。
-
shuffleCheck()
- 此方法将洗牌后的字符串的单个字符与字符串first
和second
中的字符进行比较。