📌  相关文章
📜  Java程序来检查字符串是否是两个字符串的有效改组

📅  最后修改于: 2020-09-26 18:00:01             🧑  作者: Mango

在这个例子中,我们将检查一个字符串是否是在Java中其他两个字符串的有效洗牌。

示例:检查一个字符串是否是另外两个字符串的有效改组
class Main {

  // check if result string is valid shuffle of string first and second
  static boolean shuffleCheck(String first, String second, String result) {

    // check length of result is same as
    // sum of result of first and second
    if(first.length() + second.length() != result.length()) {
      return false;
    }
    // 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 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", "Y12X"};

    // call the method to check if result string is
    // shuffle of the string first and second
    for (String result : results) {
      if (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
Y12X is not a valid shuffle of XY and 12

在上面的示例中,我们有一个名为results的字符串数组。它包含两个字符串: 1XY2Y12X 。我们正在检查这两个字符串是否是字符串 first(XY)second(12)的有效改组。

在这里,程序说1XY2XY12的有效改组 。但是, Y12X不是有效的随机播放。

这是因为Y12X更改了字符串 XY的顺序。在此,在X之前使用Y。因此,作为有效的改组,应保持字符串的顺序。