finding if two words are anagrams of each other

后端 未结 22 1079
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:51

I am looking for a method to find if two strings are anagrams of one another.

Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - ab         


        
相关标签:
22条回答
  • 2020-11-27 15:05
    1. Create a Hashmap where key - letter and value - frequencey of letter,
    2. for first string populate the hashmap (O(n))
    3. for second string decrement count and remove element from hashmap O(n)
    4. if hashmap is empty, the string is anagram otherwise not.
    0 讨论(0)
  • 2020-11-27 15:05

    How about this?

    a = "lai d"
    b = "di al"
    sorteda = []
    sortedb = []
    for i in a:
        if i != " ":
            sorteda.append(i)
            if c == len(b):
                for x in b:
                    c -= 1
                    if x != " ":
                        sortedb.append(x)
    sorteda.sort(key = str.lower)
    sortedb.sort(key = str.lower)
    
    print sortedb
    print sorteda
    
    print sortedb == sorteda
    
    0 讨论(0)
  • 2020-11-27 15:05

    If strings have only ASCII characters:

    1. create an array of 256 length
    2. traverse the first string and increment counter in the array at index = ascii value of the character. also keep counting characters to find length when you reach end of string
    3. traverse the second string and decrement counter in the array at index = ascii value of the character. If the value is ever 0 before decrementing, return false since the strings are not anagrams. also, keep track of the length of this second string.
    4. at the end of the string traversal, if lengths of the two are equal, return true, else, return false.

    If string can have unicode characters, then use a hash map instead of an array to keep track of the frequency. Rest of the algorithm remains same.

    Notes:

    1. calculating length while adding characters to array ensures that we traverse each string only once.
    2. Using array in case of an ASCII only string optimizes space based on the requirement.
    0 讨论(0)
  • 2020-11-27 15:05

    It seems that the following implementation works too, can you check?

    int histogram[256] = {0};
    for (int i = 0; i < strlen(str1); ++i) {
       /* Just inc and dec every char count and
        * check the histogram against 0 in the 2nd loop */
       ++histo[str1[i]];
       --histo[str2[i]];
    }
    
    for (int i = 0; i < 256; ++i) {
       if (histo[i] != 0)
         return 0; /* not an anagram */
    }
    
    return 1; /* an anagram */
    
    0 讨论(0)
  • 2020-11-27 15:06

    The steps are:

    1. check the length of of both the words/strings if they are equal then only proceed to check for anagram else do nothing
    2. sort both the words/strings and then compare

    JAVA CODE TO THE SAME:

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package anagram;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    /**
     *
     * @author Sunshine
     */
    public class Anagram {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException {
            // TODO code application logic here
            System.out.println("Enter the first string");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String s1 = br.readLine().toLowerCase();
            System.out.println("Enter the Second string");
            BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
            String s2 = br2.readLine().toLowerCase();
            char c1[] = null;
            char c2[] = null;
            if (s1.length() == s2.length()) {
    
    
                c1 = s1.toCharArray();
                c2 = s2.toCharArray();
    
                Arrays.sort(c1);
                Arrays.sort(c2);
    
                if (Arrays.equals(c1, c2)) {
                    System.out.println("Both strings are equal and hence they have anagram");
                } else {
                    System.out.println("Sorry No anagram in the strings entred");
                }
    
            } else {
                System.out.println("Sorry the string do not have anagram");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 15:08
    static bool IsAnagram(string s1, string s2)
            {
    
                if (s1.Length != s2.Length)
                    return false;
                else
                {
                    int sum1 = 0;
                    for (int i = 0; i < s1.Length; i++)
                    sum1 += (int)s1[i]-(int)s2[i];
                    if (sum1 == 0)
                        return true;
                    else
                        return false;
                }
            }
    
    0 讨论(0)
提交回复
热议问题