mercredi 21 juillet 2021

How to determine if two strings are permutable in java?

I am trying to determine if two strings are a permutation of each other. When I enter the following strings (see code below), the program should print that the two string are permutable. However, this is not the statement that I can see on my screen. Can anyone help me? Here is my code:

public static void main(String[] args) {
        String str1 = "abcrdt";
        String str2 = "barcdt";
        char[] arr1 = str1.toCharArray();
        Arrays.sort(arr1);
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr2);
        if (isPermutation(arr1, arr2)) {
            System.out.print("The strings are permutable.");
        } else {
            System.out.print("The strings are not permutable.");
        }
    }

    static boolean isPermutation(char[] arr1, char[] arr2) {
        if (arr1.length != arr2.length) {
            return false;
        }
        for (int i = 0; i <= arr1.length; i++) {
            for (int j = 0; j <= arr2.length; j++) {
                if (arr1[i] != arr2[j]) {
                    return false;
                }
            }
        }
        return true;
    }
}

Thank you!

Aucun commentaire:

Enregistrer un commentaire