Help me to know, why first solution works, but second isnt

Problem : Many Chefs Practice Coding Problem - CodeChef
FIrst code, which correct:

#include <bits/stdc++.h>
#define ll long long
#define yes printf("Yes\n")
#define no printf("No\n")
#define YES printf("YES\n")
#define NO printf("NO\n")
#define int long long
const int mod = 1e9 + 7;
using namespace std;

void solve() {
    string s;
    cin >> s;
    

    for (int k = s.size()-1; k >= 3; --k) {
        bool a = false, b = false, c = false, d = false;
        
        if (s[k - 3] == 'C' || s[k - 3] == '?') a = true;
        if (s[k - 2] == 'H' || s[k - 2] == '?') b = true;
        if (s[k - 1] == 'E' || s[k - 1] == '?') c = true;
        if (s[k] == 'F' || s[k] == '?') d = true;
            
        if (a && b && c && d) {
            s[k - 3] = 'C'; s[k - 2] = 'H';
            s[k - 1] = 'E'; s[k] = 'F';
        }
        
    }

    for (char &el : s) {
        if (el == '?') el = 'A';
    }
    cout << s << endl;
}


signed main() {
	//ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int t;
	scanf("%lld", &t);
	while(t--) solve();
	//cerr << "Time : " << 1000 * ((double)clock()) / CLOCKS_PER_SEC << "ms" << endl;
}

BUT if we replace solve funk with this, code wont work correct:

    string s;
    cin >> s;

    for (int k = 0; k < s.size()-3; ++k) {
        bool a = false, b = false, c = false, d = false;

        if (s[k] == 'C' || s[k] == '?') a = true;
        if (s[k + 1] == 'H' || s[k + 1] == '?') b = true;
        if (s[k + 2] == 'E' || s[k + 2] == '?') c = true;
        if (s[k + 3] == 'F' || s[k + 3] == '?') d = true;
            
        if (a && b && c && d) {
            s[k] = 'C'; s[k + 1] = 'H';
            s[k + 2] = 'E'; s[k + 3] = 'F';
        }
    }

    for (char &el : s) {
        if (el == '?') el = 'A';
    }
    cout << s << endl;
}

These two codes sequentially check all chars is string and if it valid, we replace them, but if we start at the end of the string - its valid solution, if at the begining - wrong;

Can someone explain me why it so? (im dumb, maybe very)
And sorry for my english))