Strings: Making Anagrams

  • + 0 comments

    C solution

    int deletions_reqd = 0; int len_a = strlen(a); int len_b = strlen(b); int max = 0; int i = 0;

    //printf("Running solution 2...\n");
    int32_t alphabets_a[26] = {0};
    int32_t alphabets_b[26] = {0};
    
    max = ((len_a >= len_b) ? len_a : len_b);
    //printf("max %i, len_a %i, len_b %i\n", max, len_a, len_b);
    
    if(max == 0)
    {
        goto end;
    }
    
    // accumulate repeated characters
    for(i=0; i<max; i++)
    {
        if(i < len_a)
        {
            //printf("array_a, %c, %u\n", a[i], (uint8_t)(a[i] - 'a'));
            alphabets_a[(a[i] - 'a')]++;
        }
    
        if(i < len_b)
        {
            alphabets_b[(b[i] - 'a')]++;
        }
    }        
    
    for(i=0; i<26; i++)
    {
        //printf("%c: %u\n", ('a' + i), (uint8_t) alphabets_a[i]);
        if((alphabets_a[i] > 0) || (alphabets_b[i] > 0))
        {
            if(alphabets_a[i] == alphabets_b[i])
            {
                continue;
            }
            else 
            {
                deletions_reqd += abs((alphabets_a[i] - alphabets_b[i]));
            }
        }
    }