We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
A bit of an odd solution, but the use of primes allows for a mathematic approach that doesn't require sorting and only requires traversing the arrays a single time. Not meaningfully better than storing an int in the index of the char value, but fun!
staticbooleanisAnagram(Stringa,Stringb){// Complete the functionif(a.length()!=b.length()){returnfalse;}a=a.toLowerCase();b=b.toLowerCase();int[]lookupArr={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101};inttotal=0;for(inti=0;i<a.length();i++){total+=lookupArr[a.charAt(i)-97];total-=lookupArr[b.charAt(i)-97];}if(total==0){returntrue;}returnfalse;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Anagrams
You are viewing a single comment's thread. Return to all comments →
A bit of an odd solution, but the use of primes allows for a mathematic approach that doesn't require sorting and only requires traversing the arrays a single time. Not meaningfully better than storing an int in the index of the char value, but fun!