English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste exemplo, verificaremos se uma string é uma reorganização válida de outras duas strings no Java (baralhar).
Para entender este exemplo, você deve entender o seguinteProgramação JavaTema:
class Main { //Verifica se a string de resultado é uma derivação válida dos primeiros dois strings static boolean shuffleCheck(String first, String second, String result) { //Verifica se o comprimento do resultado coincide com //A soma dos resultados do primeiro e segundo if(first.length() + second.length() != result.length()) { return false; } //Rastrear3Variáveis para cada caractere de uma string int i = 0, j = 0, k = 0; //Percorre todos os caracteres do resultado while (k != result.length()) { //Verifica se o primeiro caractere do resultado coincide com o primeiro caractere da primeira string if (i < first.length() && first.charAt(i) == result.charAt(k)) { i++; //Verifica se o primeiro caractere do resultado coincide com o primeiro caractere da segunda string } else if (j < second.length() && second.charAt(j) == result.charAt(k)) { j++; //Se os caracteres não correspondem } else { return false; } //Acessa o próximo caractere do resultado k++; } //Após acessar todos os caracteres do resultado //Se o primeiro ou o segundo tiverem alguns caracteres restantes 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"}; //Chama o método para verificar se a string de resultado é //first and second mixed for (String result : results) { if (shuffleCheck(first, second, result) == true) { System.out.println(result + "Is" + first + "And" + second + "Valid Reorganization"); } else { System.out.println(result + "Is Not" + first + "And" + second+ "Valid Reorganization"); } } } }
Output Result
1XY2 Is XY And 12 Valid Reorganization Y12X Is Not XY And 12 Valid Reorganization
In the above example, we have a string array named results. It contains two strings:1XY2and Y12X. We are checking if these two strings are valid strings first(XY) and second(12)。
Here, the program says1XY2is a valid shuffle XY and12. But, Y12X This is not a valid shuffle.
This is because Y12X Changed the order of the string XY. Here, Y is used for the previous X. Therefore, as an effective reorganization, the order of the string should be maintained.