Pls tell the error in code.. the code is to find longest substring without repeating character

int longestSubstr(string S) {
if(S.size() <= 1){
return S.size();
}

int sl = S.size();
int sf[256] = {0};
int start = 0;

int max_length = INT_MIN;
int i;
for(i=0;i<sl;i++){
    char ch = S[i];
    if(sf[ch] == 0){
        sf[ch]++;
    }
    else{
        int curr_len = i - start;
        max_length = max(max_length, curr_len);
        while(S[start] != ch){
            sf[S[start]]--;
            start++;
        }
        start++;
        sf[S[start]]++;
    }
}
return max(max_length, i-start);

}

hey @Vaibhav277 :smile:,
i would request you to save your code at ide.codingblocks.com and share your entire code here .
Thank you

Hey @Vaibhav277 :smile:,
you have attached your doubt with question Minimum Window Substring (Sliding Window) :star:, but you are asking doubt of question Length Of Longest Substring Without Repeat. I would request you to post your doubt again with respective problem you have to ask :smile:. Thank you.

hmm… actually this problem is not in course … i was solving it somewhere and test cases were not passing… so i posted it here… my output is coming correct… can u pls check if there is some error or not

You can use this one maybe it will help you

int lengthOfLongestSubstring(string s) {
if(s.size() <= 1)
return s.size();
string str;
int max_size = INT_MIN;
for(auto i = s.begin(); i != s.end(); i++)
{
if (max_size == INT_MIN)
{
str.push_back(*i);
max_size = str.length();
continue;
}
if(str.find(*i) == string::npos)
{
str.push_back(*i);
max_size = max_size < str.length()?str.length():max_size;
}
else
{
str.erase(0,str.find(*i)+1);
str.push_back(*i);
}
}
return max_size;
}

actually i was trying to use the concept of sliding window in that… so can u suggest changes in my code only

for sliding window approach you can use this

//Sliding window
        int n=s.size();
        int i(0), j(0);
        if(n==0) return 0;
        vector<int>cnt(326, 0);
        cnt[s[0]]++;
        int maxLen=1;
        while(j!=n-1){
            if(cnt[s[j+1]]!=1){
                cnt[s[j+1]]++;
                j++;
                maxLen=max(maxLen, j-i+1);
            }else{
                cnt[s[i]]--;
                i++;
            }
        }
        return maxLen;

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.