0

2 different strings were given and the question is to find out the minimum number of deletion from the given string to make both strings anagrams. I came to see this code snippet some where and all my test cases has passed, but could not understand the logic. That is, why is it subtracting 'a'? and what will be the result of it. It would be so helpful if somebody explains me the code. Thanks in advance.

int[] array=new int[26];
        for(int i=0;i<s1.Length;i++)
            array[s1[i]-'a']++;
        for(int i=0;i<s2.Length;i++)
            array[s2[i]-'a']--;
            int sum = 0;
        for(int i=0;i<26;i++)
        sum+=Math.Abs(array[i]);
        return sum;
Saranya
  • 69
  • 1
  • 4
  • Run this code in your debugger and look at the vales of `s1[i]` and of `'a'`. If you want us to help you need to show us what `s1` and `s2` are. – Dour High Arch Jun 15 '20 at 17:28
  • Mind that this code only works under the assumption that all characters in the string are lowercase. – theWiseBro Jun 15 '20 at 17:41

1 Answers1

1

s1 ans s2 are strings.

When you call s1[i], you are accessing the i-th char of s1, which is also an int that represents the position of that char in the ASCII table.

For example, a is the 97-th character in ASCII.

When you do s1[i] - 'a', you are basically doing s1[i] - 97.

If s1[i] is a, then s1[i] - 'a' will be 0. This will make it easy to convert chars from a to z for ints from 0 to 25 and put them in an array.


CODE ANALYSIS

//create new array to represent the count for each character from 'a' to 'z'
int[] array = new int[26];

//count the caracters from s1. If there is 'a', add 1 to array[0], 
//if there is 'b', add 1 to array[1], ..., if there is 'z', add 1 to array[25].
for(int i = 0; i < s1.Length; i++) array[s1[i] - 'a']++;

//do the same thing, but subtracting. If there is 'a', subtract 1 from array[0], etc.
for(int i = 0; i < s2.Length; i++) array[s2[i] - 'a']--;

int sum = 0;

//for each letter, the absolute value of the matrix slot will say
//the positive difference between the 2 strings, so you know that
//if Math.Abs(array[0]) = 2, you need to remove 2 'a' from the strings.
for(int i = 0; i < 26; i++) sum += Math.Abs(array[i]);

return sum;
Daniel
  • 7,357
  • 7
  • 32
  • 84