Answers for "longest substring with k unique characters"

C++
0

longest substring with k unique characters

//I will encourage to first understand the problem then implement it on your know and do not just copy paste this code :) Regards
#include <bits/stdc++.h>

using namespace std;

int main()
{
    string str;
    cout<<"Enter the string :"<<endl;
    cin>>str;
    int k;
    cout<<"Enter the number of unique characters required:"<<endl;
    cin>>k;
    map<char,int>mp;
    int j=0;
    int i=0;
    int mx=INT_MIN;
    int l=str.size();
    while(j<l)
    {
        mp[str[j]]++;
        if(int(mp.size())<k)
        {
            j++;
        }
        else if(int(mp.size())==k)
        {
            mx=max(mx,j-i+1);
            j++;
        }
        else
        {
            while(int(mp.size())>k)
            {
                mp[str[i]]--;
                if(mp[str[i]]==0)
                {
                    mp.erase(str[i]);
                }
                i++;
            }
            j++;
        }
    }
  cout<<mx<<endl;

    return 0;
}
Posted by: Guest on June-24-2021

Code answers related to "longest substring with k unique characters"

Browse Popular Code Answers by Language