lundi 25 septembre 2017

Counting minimum no. of char. to delete from two strings to make them anagrams

I have written following function to return no. of characters to delete from two strings to make them anagrams.

  int number_needed(string a, string b) {
  static int c;
  for(int i=0;i<=a.length();i++)    //loop over string a
      { char ch=a[i];
         int found=b.find(ch);
         if( found==string::npos)   //if character at a[i] not found in b
            {
              a.erase(i,1);          //delete character in a[i]
              c++;                   //inc. count c
            }
      }
  for(int i=0;i<=b.length();i++)       // repeat above looping for b string
      { char ch=b[i];
        int found=a.find(ch);
        if( found==std::string::npos)
           {
             b.erase(i,1);
             c++;
           }
      }
   return c;                           //finaly return no. of char. deleted
 }

I want to know if I have done everything right or not and whether my idea is fine in the context of problem. Also, can you make me understand the following code for the same problem which was given as solution.

 int number_needed(string a, string b) {
 auto count = 0;
 vector<int> freq(26, 0);
 for (auto c : a) { ++freq[c - 'a']; }
 for (auto c : b) { --freq[c - 'a']; }
 for (auto val : freq) { count += abs(val); }
 return count;
 }

Aucun commentaire:

Enregistrer un commentaire