Solution:
Leetcode 003: Longest Substring Without Repeating Characters
Idea:
For this question, we create an array to record the previous occurrence index of certain character. For example, a[(int)'A']
represents the last occurrence index of 'A'
. Also, tow pointers, beg
and end
, is needed. beg
points to where we start our substring, and end
points to the end of the longest substring starting from beg
.
We continuously move end
pointer back until we encounter i
such that beg <= a[(int)s.charAt(i)]
, which means there will be repeating characters (s.charAt(a[(int)s.charAt(i)])
and s.charAt(i)
should be the same) if we add current character to the substring. At this time, we calculate the lenght current substring and compare to the max
.
Extra:
After finishing the scanning, we need to check again the lenght of substring from beg
to end
, comparing with the max
length, before return the result.