#3 Longest Substring Without Repeating Characters

Posted lvbaiyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#3 Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

#3 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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

利用滑动窗口和哈希map。

技术图片

首先对字字符串进行遍历,每读取一个元素,都要找到上一个与当前元素重复的index,记为flag。利用字典储存某个元素及其最后出现的位置。

时间复杂度:(O(n)),依次遍历

空间复杂度:(O(1)),常数级存储空间用于储存字符串

代码解释

line 9:flag从-1开始记录,因为第一个元素开始 的长度为(0-(-1)=1)

line 19:只有在存入新字符的时候才会更新最长不重复子串的常数

Github

以上是关于#3 Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

longest-substring-with-at-least-k-repeating-characters

LeetCode 395. Longest Substring with At Least K Repeating Characters

395. Longest Substring with At Least K Repeating Characters

3. Longest Substring Without Repeating Characters

Leetcode: Longest Substring with At Least K Repeating Characters

395. Longest Substring with At Least K Repeating Characters