From Soiled Mousedeer, 1 Week ago, written in Text.
Embed
  1. def longestSubstring(s, n) {
  2.         //Size of input String
  3.         def z = s.size()
  4.        
  5.         //Map to keep track of characters in current range we are interested in
  6.         def m = [:]
  7.  
  8.         //Max size of substring with n unique values
  9.         int x = 0
  10.        
  11.         //Left and right pointers that will keep track of working range
  12.         int l = 0
  13.         int r = 0
  14.        
  15.         for(; r < z; r++){
  16.                 //Add to map or increase count if already present
  17.                 def c = s[r]
  18.                 m[c] = m[c] ? m[c]+1 : 1
  19.                
  20.                 //If right - left is greater than max update max
  21.                 x = x < r-l ? r-l : x
  22.                
  23.                 //Check if the map contains more than n unique characters
  24.                 //Loop until the map contains
  25.                 //less than or equal to n unique characters
  26.                 for(def t = s[l]; m.size() > n; t= s[++l])
  27.                         //Subtract one from the count value of the left pointer.
  28.                         //Remove it if count goes to 0
  29.                         --m[t] ?: m.remove(t)
  30.                
  31.         }
  32.         //Check if unique count is larger than string size return 0 if it is
  33.         //Else return max of right - left and x
  34.         n > z ? 0 : x < z - l ? z - l : x
  35. }