What is an easy way to tell if a list of words are anagrams of each other?

前端 未结 10 1973
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 18:38

How would you list words that are anagrams of each other?

I was asked this question when I applied for my current job.

orchestra can be rearrang

相关标签:
10条回答
  • 2020-12-03 19:08

    Tried hashcode logic for anagram gives me false output

    public static Boolean anagramLogic(String s,String s2){
        char[] ch1 = s.toLowerCase().toCharArray();
            Arrays.sort(ch1);
            char[] ch2= s2.toLowerCase().toCharArray();
            Arrays.sort(ch2);
            return ch1.toString().hashCode()==ch2.toString().hashCode(); //wrong
        }
    

    to rectify this code, below is the only option I see,appreciate any recommendations

    char[] ch1 = s.toLowerCase().toCharArray();
            Arrays.sort(ch1);
            char[] ch2= s2.toLowerCase().toCharArray();
            Arrays.sort(ch2);
            return Arrays.equals(ch1,ch2);
        }
    
    0 讨论(0)
  • 2020-12-03 19:09

    Put all the letters in alphabetical order in the string (sorting algorithm) and then compare the resulting string.

    0 讨论(0)
  • 2020-12-03 19:13

    The following algorithm should work:

    1. Sort the letters in each word.

    2. Sort the sorted lists of letters in each list.

    3. Compare each element in each list for equality.

    0 讨论(0)
  • 2020-12-03 19:18

    Interestingly enough, Eric Lippert's Fabulous Adventures In Coding Blog dealt with a variation on this very problem on February 4, 2009 in this post.

    0 讨论(0)
  • 2020-12-03 19:26

    Sort the letters and compare (letter by letter, string compare, ...) is the first things that comes to mind.

    0 讨论(0)
  • 2020-12-03 19:27

    Well Sort the words in the list.

    if abc, bca, cab, cba are the inputs, then the sorted list will be abc, abc, abc, abc.

    Now all of their Hash codes are equal. Compare the HashCodes.

    0 讨论(0)
提交回复
热议问题