mardi 21 septembre 2021

IF statement giving wrong answer whereas ELSE IF is working fine

I am solving Count Occurences of Anagrams question on gfg link https://practice.geeksforgeeks.org/problems/count-occurences-of-anagrams5839/1#

int search(string ana, string s) {

    unordered_map<char, int> m;
    for(auto it : ana) m[it]++;

    int k=ana.length();
    int count=m.size();
    
    int i=0, j=0;
    int ans=0;
    
    while(j<s.length()){
    
        if(m.find(s[j])!=m.end()){
            m[s[j]]--;
            if(m[s[j]]==0) count--;
        }
         
        if(j-i+1<k) j++;
        
       if(j-i+1==k){  //**else if works**
           
            if(count==0) ans++;
           
            if(m.find(s[i])!=m.end()){
                m[s[i]]++;
                if(m[s[i]]==1) count++;
            }

            i++;
            j++;
        }
    }
    return ans;
}

This code works when using else if(j-i+1==k) but when using simply if(j-i+1==k) it gives the wrong answer. for test case: s = forxxorfxdofr ana = for Output: 3 but when using only if it gives Output :0

Also this is the first time I've posted on Stack Overflow so apologies if the question or formatting is out of place.

Aucun commentaire:

Enregistrer un commentaire