Checking strings against each other (Anagrams)

后端 未结 23 1963
忘了有多久
忘了有多久 2020-11-30 10:55

The assignment is to write a program that accepts two groups of words from the user and then prints a \"True\" statement if the two are anagrams (or at least if all the lett

23条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 11:18

    Anagrams are the two different words formed with same characters: For eg: EAT and TEA likewise there can be numerous examples.

    One good way to see if give two words or sentences are anagrams is to set a counter array of size 256, and initially set all the values to 0. (This can be a good option if the input is bigger, at least than a few words) Now start reading the first string(word or a sentence), and increment its corresponding ASCII location in the array by one. Repeat this for the complete string. Now start reading the second string and keep decreasing the corresponding ASCII counter of each letter in the array. Finally, parse the array; if all the values are zero then the inputs were anagrams otherwise not. Following is the commented code for the better understanding.

    #include
    #include
    
    using namespace std;
    
    bool is_anagram(string s1, string s2)
    {
        //Following statement chechs the base condition; if either of the strings is empty,                                  
        //return False
        if(s1.length() == 0 || s2.length() == 0)
            return false;
    
        //initializing the counter array and setting it's values to 0
        int counter[256] = {0};
    
        //Calculating the lengths of both the strings
        int len1 = s1.length();
        int len2 = s2.length();
    
        //Following is also a base condition that checks whether the strings are equal in 
        //length, if not we return False
        if(len1 != len2)
            return false;
    
        //Following for loop increments the values of the counter array for the first  
        //string
        for(int i = 0; i < len1; i++)
        {
            counter[s1[i]]++;
        }
    
        //This for loop decrements the values of the counter array for the second string
        for(int i = 0; i < len2; i--)
        {
            counter[s2[i]]--;
        }
        //Now we check whether the counter array is empty/(or as it was initialized); if               
        //yes then the two strings are anagrams
        for(int i = 0; i < 256; i++)
        {
            if(counter[i] != 0)
                return false;
        }
    
        return true;
    }
    

提交回复
热议问题