63. leetCode3.Longest Substring Without Repeating Characters【最长不重复子串】

xiaoxiao2021-02-28  58

【题目】:

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.

【分析】:youtube讲解 使用字典dict来进行计算,pointer指的是头指针

步骤1:检查dict中是否存在当前的字符,若存在则更新pointer位置

步骤2:计算max,为index - pointer + 1

步骤3:更新dict,将已存在的字符的索引更新为当前的索引index

【代码】:

class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ tempDict = {} pointer = 0 maxLen = 0 for key, value in enumerate(s): if value in tempDict: pointer = max(pointer, tempDict[value]+1) maxLen = max(maxLen, key - pointer + 1) tempDict[value] = key return maxLen

转载请注明原文地址: https://www.6miu.com/read-2632677.html

最新回复(0)