Search code examples
c++stringanagram

Giving Wrong output


I was trying Leetcode problem https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/

It is to return minimum number of letters that needs to be changed to make the two strings anagrams. However when pass a string "leetcode" and other string "practise" , it should give output as 5 but giving 3.

LOGIC:

  1. Start a for loop taking letters of first string one by one. Say take 'L'
  2. Then count how many letters i.e 'L' are there in the first string. Store its value in val i.e. val = 1;
  3. Then similarly count the number of 'L' in second string and store the value in count i.e. count=0;
  4. Then if val>count , subtract val - count i.e. 1-0 = 1 and store it in sum;
  5. Now similarly do all the above 4 steps in every letter of the 1st string and add every result in fsum i.e. fsum+=sum;
  6. Thus fsum will tell the number of letters needed to be changed.

Could anybody help me in finding my mistake ?

class Solution {
public:
    int minSteps(string s, string t) {
        vector<char> v1;
        char c;
        int flag;
        int val=0;
        int count=0;
        int len=0;
        int sum=0;
        int d=0;
        int fsum=0;

        for(int i=0;i<s.length();i++){
            c=s[i];
            flag=0;

            vector<char> :: iterator it = find(v1.begin(),v1.end(),c);

            if(it != v1.end()){ 
                flag=1;
                break;
            }
            else 
            if(flag==0){
                v1.push_back(c);

                len=s.length();
                d=0;
                val=0;
                while(len){
                    if(c==s[d]) val++;
                    d++; len--;
                } 

                //comparison in 2nd string
                len=t.length();
                d=0;
                while(len){
                    if(c==t[d]) count++;
                    d++; len--;
                }

                if(val>count){ 
                    sum=val-count;
                    fsum+=sum;
                    val=count=0;
                }
            }
        }
        return fsum;
    }
};

Solution

  • Your logic seems to be 'about' right. However, check the following piece of your code:

    vector<char> :: iterator it = find(v1.begin(),v1.end(),c);
    if(it != v1.end()){ 
            flag=1;
            break;
    }
    

    What this says is, if character c has already been seen before, BREAK out of the loop. I assume what you meant was CONTINUE with the next iteration of the loop.

    This is because when you break, you do not break the loop over the vector v1 (I think that's what you assumed). Rather you break the loop over the string s.