firstIndex
to store the first occurrence of each character.ans
to -1
to represent no valid substring found initially.i
of the string s
:
s[i]
is in firstIndex
, calculate the length of the substring as i - firstIndex[s[i]] - 1
and update ans
if this length is larger.firstIndex[s[i]]
to i
to record the first occurrence of the character.ans
as the final result.