Sheikh Rahman Sheikh Rahman - 16 days ago 8
Java Question

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

That is a question from Cracking the coding interview.Below is my code:

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


}
}


Question: When I use Tom(1st) and 2nd Mot/moT (tried different variations), I always get Not perm of 1st word. There are answers in the book, I want to know whats wrong with this logic. Thank in advance.

Answer

As mentioned in the comment s1.toCharArray()==s2.toCharArray() is wrong because you are not really comparing values in the array just the references of those 2 newly created arrays. You should sort those arrays Arrays.sort And then use Arrays.equals to compare those arrays.