Java Given 2 Strings编写一种方法来判断一个是否是另一个的排列

时间:2016-11-14 20:22:03

标签: java permutation

这是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(尝试不同的变化)时,我总是得到第一个字的非烫发。书中有答案,我想知道这个逻辑有什么不对。预先感谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

想法是在标记所有内容之前,在两个字符串/字符串数组中标记相同字符的条目。 (在检查相同长度的字符串后)

    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 /基于算法)。