In questo esempio, controlleremo se una stringa è lo shuffle valido di altre due stringhe in Java.
Per comprendere questo esempio, è necessario conoscere i seguenti argomenti di programmazione Java:
- Java String
- Java while e do … while Loop
Esempio: controlla se una stringa è uno shuffle valido di altre due stringhe
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); ) ) ) )
Produzione
1XY2 è uno shuffle valido di XY e 12 Y12X non è uno shuffle valido di XY e 12
Nell'esempio precedente, abbiamo un array di stringhe denominato risultati. Contiene due stringhe: 1XY2 e Y12X. Stiamo controllando se queste due stringhe sono valide shuffle di stringhe prima (XY) e seconda (12).
Qui, il programma dice che 1XY2 è uno shuffle valido di XY e 12. Tuttavia, Y12X non è uno shuffle valido.
Questo perché Y12X ha modificato l'ordine della stringa XY. Qui, Y è usato prima di X. Quindi, per essere un valido shuffle, l'ordine della stringa dovrebbe essere mantenuto.
Nota : il programma si confonde se le lettere iniziali di due stringhe corrispondono. Ad esempio, se ab12 e abb34 sono due stringhe, abbab1234 è uno shuffle valido.
Tuttavia, il programma tratterà le prime due lettere ab come parte della prima stringa. Per questo motivo, la terza lettera b non corrisponde né alla terza lettera della prima stringa (1), né alla prima lettera della seconda stringa (a).