Program Java pentru a verifica dacă un șir este un amestec valid de două șiruri distincte

În acest exemplu, vom verifica dacă un șir este amestecarea valabilă a altor două șiruri în Java.

Pentru a înțelege acest exemplu, ar trebui să aveți cunoștințele despre următoarele subiecte de programare Java:

  • Șir Java
  • Java while și do … while Buclă

Exemplu: Verificați dacă un șir este un amestec valid al altor două șiruri

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

Ieșire

 1XY2 este un amestec valid de XY și 12 Y12X nu este un amestec valid de XY și 12

În exemplul de mai sus, avem o matrice de șiruri denumită rezultate. Conține două șiruri: 1XY2 și Y12X. Verificăm dacă aceste două șiruri de caractere sunt valide amestec de șiruri primul (XY) și al doilea (12).

Aici, programul spune că 1XY2 este un amestec valid de XY și 12. Cu toate acestea, Y12X nu este un amestec valid.

Acest lucru se datorează faptului că Y12X a modificat ordinea șirului XY. Aici, Y este folosit înainte de X. Prin urmare, pentru a fi un amestec valid, ordinea șirului ar trebui menținută.

Notă : Programul se confundă dacă literele inițiale din două șiruri se potrivesc. De exemplu, dacă ab12 și abb34 sunt două șiruri, atunci abbab1234 este un amestec valid.

Cu toate acestea, programul va trata primele două litere ab ca parte a primului șir. Din această cauză, a treia literă b nu se potrivește atât cu a treia literă din primul șir (1), cât și cu prima literă din al doilea șir (a).

Articole interesante...