Programa Java para verificar se uma string é um embaralhamento válido de duas strings distintas

Neste exemplo, vamos verificar se uma string é o embaralhamento válido de duas outras strings em Java.

Para entender este exemplo, você deve ter conhecimento dos seguintes tópicos de programação Java:

  • Java String
  • Java while e do … while Loop

Exemplo: verifique se uma string é uma mistura válida de duas outras strings

 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); ) ) ) )

Resultado

 1XY2 é um shuffle válido de XY e 12 Y12X não é um shuffle válido de XY e 12

No exemplo acima, temos uma matriz de strings chamada results. Ele contém duas strings: 1XY2 e Y12X. Estamos verificando se essas duas strings são embaralhadas válidas primeiro (XY) e depois (12).

Aqui, o programa diz que 1XY2 é um shuffle válido de XY e 12. No entanto, Y12X não é um shuffle válido.

Isso ocorre porque Y12X alterou a ordem da string XY. Aqui, Y é usado antes de X. Portanto, para ser um embaralhamento válido, a ordem da string deve ser mantida.

Nota : O programa fica confuso se as letras iniciais de duas strings forem iguais. Por exemplo, se ab12 e abb34 são duas strings, então abbab1234 é um shuffle válido.

No entanto, o programa tratará as duas primeiras letras ab como parte da primeira string. Devido a isso, a terceira letra b não combina com a terceira letra da primeira string (1) e a primeira letra da segunda string (a).

Artigos interessantes...