Java-programm, et kontrollida, kas string on kahest erinevast stringist sobiv segamine

Selles näites kontrollime, kas string on Java kahe teise stringi sobiv segamine.

Selle näite mõistmiseks peaksid teil olema teadmised järgmistest Java programmeerimise teemadest:

  • Java string
  • Java ajal ja tee … Loopi ajal

Näide: kontrollige, kas string on kahe teise stringi sobiv segamine

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

Väljund

 1XY2 on kehtiv XY ja 12 ja 12 Y12X pole XY ja 12 juhuslik segamine

Ülaltoodud näites on meil stringide massiiv nimega tulemused. See sisaldab kahte stringi: 1XY2 ja Y12X. Kontrollime, kas need kaks stringi kehtivad kõigepealt stringide segamine (XY) ja teine ​​(12).

Siin ütleb programm, et 1XY2 on kehtiv XY ja 12. juhuslik segamine. Kuid Y12X ei ole kehtiv segamine.

Seda seetõttu, et Y12X on muutnud stringi XY järjekorda. Siin kasutatakse Y-d enne X-i. Seega, et olla korrektne segamine, tuleks säilitada stringide järjekord.

Märkus . Programm läheb segadusse, kui kahe stringi algustähed kattuvad. Näiteks kui ab12 ja abb34 on kaks stringi, siis abbab1234 on kehtiv juhus .

Kuid programm käsitleb kahte esimest ab- tähte esimese stringi osana. Seetõttu ei klapi kolmas täht b nii esimese stringi (1) kolmanda tähega kui ka teise stringi (a) esimese tähega.

Huvitavad Artiklid...