I gave a coding test online in which a question was asked:
Given a string containing only latin lowercase letters and question mark, your task is to replace the question marks with lowercase letters in such a way that the substrings formed by replacing is of max length. Return the max length of the substring consisting of same lowercase letters.
Ex: “a??a”
output: 4
Explanation: replacing both ‘?’ with ‘a’ results in “aaaa” which has max length of 4
Ex: “ab?ca”
output: 2
Explanation: replacing ‘?’ with either ‘b’ or ‘c’ reults in a max substing of same characters of length 2.
To solve this question I was planning to use sliding window approch but in the end came with this:
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int n=s.length();
int ans=INT_MIN;
int i=0;
int j=0;
char ch='#';
for(;i<n;i++){
if(s[i]=='?') continue;
if(ch=='#') ch=s[i];
if(ch!=s[i]){
if(s[i-1]!='?'){
ch=s[i];
ans=max(ans,i-j);
j=i;
}
else{
ch=s[i];
ans=max(ans,i-j);
int temp=i;
while(temp>=1){
if(s[temp]=='?' && s[temp-1]!='?') break;
temp--;
}
j=temp;
}
}
}
ans=max(ans,i-j);
cout<<ans<<endl;
}
return 0;
}
It’s little messy but my general thought was to ignore any question marks, check what the first lowercase letter is and when I encounter a character that is different than the previous one check if it is a letter or question mark. If its a letter then take a pointer and place it to the first position of the new character and in the other case, take the pointer to mark the previous first occurence of ‘?’. For ex in “ab??cd”, the pointer will go to the first question mark at index 2.
When I submitted this question I had some other cases like,
“?ab”
“abb?c??d”
“ab?cc?d”.
I was in a time constraint so I wasn’t able to think much about wrting cleaner or more optimised code but now that I looked at it again I’m stll confused to any particular thing I missed or can do to improve it.
In that test this code didn’t pass any test cases and I don’t understand why. I need help in figuring out what is wrong or help with some parts that might need to change to make this work. Thanks