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

前端 未结 10 1974
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27
    public static void main(String[] args) {
    
        String s= "abc";
        String s1="cba";
    
    
    
         char[] aArr = s.toLowerCase().toCharArray(); 
         char[] bArr = s1.toLowerCase().toCharArray();
    
      // An array to hold the number of occurrences of each character
      int[] counts = new int[26]; 
    
      for (int i = 0; i < aArr.length; i++){
       counts[aArr[i]-97]++;  // Increment the count of the character at respective position
       counts[bArr[i]-97]--;  // Decrement the count of the character at respective position
      }
    
      // If the strings are anagrams, then counts array will be full of zeros not otherwise
      for (int i = 0; i<26; i++){
       if (counts[i] != 0)
        return false;
      } 
    
    0 讨论(0)
  • 2020-12-03 19:33

    Good thing we all live in the C# reality of in-place sorting of short words on quad core machines with oozles of memory. :-)

    However, if you happen to be memory constrained and can't touch the original data and you know that those words contain characters from the lower half of the ASCII table, you could go for a different algorithm that counts the occurrence of each letter in each word instead of sorting.

    You could also opt for that algorithm if you want to do it in O(N) and don't care about the memory usage (a counter for each Unicode char can be quite expensive).

    0 讨论(0)
  • 2020-12-03 19:33
    1. compare length (if not equal, not a chance)
    2. make a bit vector of the length of the strings
    3. for each char in the first string find occurrences of it in the second
    4. set the bit for the first unset occurrence
    5. if you can find one stop with fail
    0 讨论(0)
  • 2020-12-03 19:35

    Sort each element (removing whitespace) and compare against the previous. If they are all the same, they're all anagrams.

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