Longest Substring Without Repeating Characters

Given a string S, find the length of the longest substring without repeating characters.


Example 1:

Input:
S = "codemummyccode"
Output:
6
Explanation:
Longest substring is
"codemu".

Example 2:

Input:
S = "ABDEFGABEF"
Output:
6
Explanation:
Longest substring is
"BDEFGA" and "DEFGAB".




c++ implementation:

    int longestUniqueSubsttr(string s)
    {
        int n=s.length();
       unordered_set<char>set;
        
       int l=0;int ml=0;int r=0;int len=0;
       while(r<n)
       {
           
              while(set.find(s[r])!=set.end())
              {
                 set.erase(s[l]);
                 l++;
               }
              
              set.insert(s[r]);
               len=r-l+1;
               r++;

          ml=max(len,ml);
       }
        return ml;
    }

time complexity:0(2n)≈ 0(n)

space complexity:0(n)




c++ implementation:

    int longestUniqueSubsttr(string s)
    {
        int n=s.length();
       unordered_set<char>set;
        
       int l=0;int ml=0;int r=0;int len=0;
       while(r<n)
       {
           
              while(set.find(s[r])!=set.end())
              {
                 set.erase(s[l]);
                 l++;
               }
              
              set.insert(s[r]);
               len=r-l+1;
               r++;

          ml=max(len,ml);
       }
        return ml;
    }

time complexity:0(n)

space complexity:0(n)




No comments

darkmode