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 to map each character to its position. When iterate through the characters of String s, if find a repeating
character, clear the map and start the iteration from the position of the last seen character. The complexity will be O(n!) worst case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null) {
return 0;
}
int longestLength = 0;
int currentLength = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
if (longestLength < currentLength) {
longestLength = currentLength;
}
currentLength = 0;
i = map.get(s.charAt(i));
map.clear();
continue;
}
map.put(s.charAt(i), i);
currentLength++;
}
return longestLength > currentLength ?
longestLength : currentLength;
}
}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null) {
return 0;
}
int longestLength = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0, start = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
start = Math.max(start, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
longestLength = Math.max(i - start + 1, longestLength);
}
return longestLength;
}
}