Java 给定 2 个字符串,编写一个方法来确定一个是否是另一个的排列

Java Given 2 Strings write a method to decide if one is a permutation of the other

这是 Cracking the coding 的问题 interview.Below 是我的代码:

class PalinDrome {

    public static Scanner userinput = new Scanner(System.in);
    public static void main(String [] args){

        //1st input from user
        System.out.println("Enter 1st string: ");
        String s1= userinput.next().toLowerCase();

        // convert 1st string to char Array

        char [] charS1= s1.toCharArray();

        System.out.println(charS1);

        //2nd input from user
        System.out.println("Enter 2nd string: ");
        String s2= userinput.next().toLowerCase();

        // convert 2nd string to char Array

        char [] charS2= s2.toCharArray();

        System.out.println(charS2);

        if(s1.length()==s2.length() && s1.toCharArray()==s2.toCharArray()){
            System.out.println(" Word 2 is Perm of 1st word");
        }
        else{
            System.out.println(" Word 2 is not Perm of 1st word");
        }


    }
}

问题:当我使用 Tom(1st) 和 2nd Mot/moT(尝试了不同的变体)时,我总是得到 Not perm of 1st word。书上有答案,我想知道这个逻辑有什么问题。预先感谢。

如评论中所述,s1.toCharArray()==s2.toCharArray() 是错误的,因为您实际上并没有比较数组中的值,只是比较了这两个新创建的数组的引用。 您应该对这些数组进行排序 Arrays.sort 然后使用 Arrays.equals 来比较这些数组。

这是一个使用集合或排序的解决方案。 ^^

想法是标记两个 Strings/char 数组中具有相同字符的条目,直到所有内容都被标记为止。 (检查相同长度的字符串后)

    package PermuteString;

public class Permutation {

public static void main(String[] args) {

    String a = "yalla";

    String b = "allay";

    String c = "allas";

    Permutation permutation = new Permutation();

    if (permutation.isPermutationWithoutCollection(a, b))
        System.out.println(a + " is permutation of " + b);

    if (!permutation.isPermutationWithoutCollection(a, c))
        System.out.println(a + " is not a permutation of " + c);

}

public boolean isPermutationWithoutCollection(String string1, String string2) {

    if (string1.length() != string2.length()) {
        return false;
    }

    char[] a = string1.toLowerCase().toCharArray();

    char[] b = string2.toLowerCase().toCharArray();

    for (int i = 0; i < a.length; i++) {

        boolean unChanged = true;

        for (int k = 0; k < b.length; k++) {

            if (a[i] == b[k]) {
                a[i] = 'A';
                b[k] = 'B';
                unChanged = false;
                break;
            }

        }

        if (unChanged) {
            //System.out.println("wawawa");
            return false;
        }
    }

    return true;
}

}

产量:

yalla 是 allay 的排列

yalla 不是 allas 的排列

真的取决于面试的主题(基于使用java/基于算法)。