Description
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
Explanation
We use two pointers technique to solve the problem. One slow pointer i, one fast pointer j.
We also add a HashSet to store the characters which have been visited by j pointer to help detect repeating characters.
We keep moving j pointer right further.
- If current s.charAt(j) character is not in the HashSet, we add the character to the HashSet and keep moving j further.
- If current s.charAt(j) character is in the HashSet, we remove the character i is visiting and move i forward. At this point, we found the maximum size of substrings without duplicate characters start with index i. We move i pointer one step further.
When j pointer iterates all the characters of the string, we get the max length of the longest substring without repeating characters.
Java Solution
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
HashSet<Character> set = new HashSet<>();
int i = 0;
int j = 0;
while (j < s.length()) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
maxLength = Math.max(maxLength, j - i);
} else {
set.remove(s.charAt(i));
i++;
}
}
return maxLength;
}
}
Python Solution
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
counter = {}
j = 0
longest = 0
for i in range(len(s)):
while j < len(s) and s[j] not in counter:
longest = max(longest, j - i + 1)
counter[s[j]] = counter.get(s[j], 0) + 1
j += 1
counter[s[i]] -= 1
if counter[s[i]] == 0:
del counter[s[i]]
return longest
- Time complexity: O(n).
- Space complexity: O(m). m is the size of the charset.
It is a best solution very popular and helpful:
https://www.youtube.com/watch?v=-QPgQJl_CDg&ab_channel=EricProgramming