Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”
, the answer is “abc”
, which the length is 3.
Given “bbbbb”
, the answer is “b”
, with the length of 1.
Given “pwwkew”
, the answer is “wke”
, with the length of 3. Note that the answer must be a substring, “pwke”
is a subsequence and not a substring.
Setting the Test Case before writing code is very important!
For problems which ask for a substring, we need to think about Two Pointers.
1. Version 1
I used a Map
character, clear the map and start the iteration from the position of the last seen character. The complexity will be O(n!)
worst case.
|
|
2. Two Pointers
Use two pointers: start
indicating the start position of the substring currently working on.
And i
to scan the characters of the string s. Whenever s.charAt(i) is in the map, set the start pointer to the max of start and the
position of s.charAt(i). The reason to use max
is to make sure start
going forward.
|
|