C# O(n) slide window


  • 0
    Y
    public class Solution {
        public int LengthOfLongestSubstringKDistinct(string s, int k) {
            Dictionary<char,int> disHash=new Dictionary<char,int>();
            int start=0,end=0,dist=0,max=0;
            while(end<s.Length)
            {
                while(end<s.Length&&dist<=k)
                {   
                    if(!disHash.ContainsKey(s[end]))
                    {
                        dist++;
                        disHash.Add(s[end],1);
                    }
                     else
                        disHash[s[end]]++;
                        
                    if(dist<=k)
                        max=Math.Max(max,end-start+1);
                    
                    end++;
                }
                
                disHash[s[start]]--;
                if(disHash[s[start]]==0)
                {
                    dist--;
                    disHash.Remove(s[start]);
                }
                start++;   
            }
            
            return max;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.