题目:3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
思路
本题使用 sliding Window 的解法,设 left 和 right,用 hashmap 记录字母出现频率。向右移动 right,如果当前字母出现次数不为 0,代表该 no repeating substring 已经到终点,此时右移 left,并减一 map 中的频率,直到 counts[right]频率为 0,则新的 no repeating substring 开始。 时间复杂度为 O(n),空间复杂度 O(1)。