#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

posted @ 2020-03-22 19:14  Lyu1997  阅读(111)  评论(0编辑  收藏  举报