Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active October 15, 2015 10:14
Show Gist options
  • Save gavinking/d5fe40c07a81378b4f84 to your computer and use it in GitHub Desktop.
Save gavinking/d5fe40c07a81378b4f84 to your computer and use it in GitHub Desktop.
"Finds the (last) longest substring that contains
at most two unique characters"
String longest2UniqueCharSubstring(String s)
=> let (init = [[0, 0, 0, 0], 0, '\0', '\0'],
mpos = s.fold(init)((acc,ch)
=> let ([[mb,me,cb,ce],cb1,ch0,ch1] = acc,
ce1 = ce+1,
max = (Integer b, Integer e)
=> me-mb > e-b then [mb,me,b,e]
else [b,e,b,e])
if (ch==ch1) then [max(cb,ce1),cb1,ch0,ch1]
else if (ch==ch0) then [max(cb,ce1),ce,ch1,ch]
else [max(cb1,ce1),ce,ch1,ch])[0],
pos=mpos[0],
len=mpos[1]-pos)
s[pos:len];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment