Anagrams – how can I pass the below two test cases

  • A+

Here is my code for whether two strings are anagrams or not

static boolean isAnagram(String a, String b) {     if (a.length() != b.length()) return false;     a = a.toLowerCase();     b = b.toLowerCase();     int m1=0;     for(int i=0;i<a.length();i++){         m1 += (int)a.charAt(i);         m1 -= (int)b.charAt(i);      }         return m1==0; } 

My code fails for two test cases

  • case 1: String a="xyzw";and String b="xyxy";
  • case 2: String a="bbcc"; and String b="dabc";

can anyone help me passing the above two cases?


I think your code doesn't work because you sum up the code of characters but maybe answer is zero however their are not equal, for example: "ad" "bc"
the better way is to do this is to sort characters of strings, if they has same array length and same order, so two string are anagram.

static boolean isAnagram(String str1, String str2) {     int[] str1Chars = str1.toLowerCase().chars().sorted().toArray();     int[] str2Chars = str2.toLowerCase().chars().sorted().toArray();     return Arrays.equals(str1Chars, str2Chars); } 

I hope this help you. (it is a little hard because I use stream to create and sort array of characters)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: