V tem primeru bomo preverili, ali je niz veljavno mešanje dveh drugih nizov v Javi.
Če želite razumeti ta primer, morate poznati naslednje programske teme Java:
- Java Java
- Java while in do … while Loop
Primer: Preverite, ali je niz veljavno mešanje dveh drugih nizov
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); ) ) ) )
Izhod
1XY2 je veljavna premestitev XY in 12 Y12X ni veljavna premestitev XY in 12
V zgornjem primeru imamo niz nizov z imenom rezultati. Vsebuje dva niza: 1XY2 in Y12X. Preverjamo, ali sta ta dva niza veljavna mešanje nizov prvi (XY) in drugi (12).
Tu program pravi, da je 1XY2 veljaven naključni premik XY in 12. Vendar Y12X ni veljaven naključni premestitev.
To je zato, ker je Y12X spremenil vrstni red nizov XY. Tu se Y uporablja pred X. Zato je treba za veljavno premeščanje ohraniti vrstni red nizov.
Opomba : Program se zmede, če se začetni črki dveh nizov ujemata. Če sta na primer ab12 in abb34 dva niza, potem je abbab1234 veljavno naključno mešanje.
Vendar bo program prvi dve črki ab obravnaval kot del prvega niza. Zaradi tega se tretja črka b ne ujema tako s tretjo črko prvega niza (1) kot s prvo črko drugega niza (a).