目录

xffish 的个人博客

记录精彩的程序人生

X

LeetCode-3.无重复字符的最长子串

LeetCode-3.无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。

示例 1:

输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。

请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

英文原文:
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.

我的解答:

 1class Solution:
 2    def lengthOfLongestSubstring(self, s):
 3        """
 4        :type s: str
 5        :rtype: int
 6        """
 7        start = max_len = 0
 8        used = {}
 9    
10        for i, item in enumerate(s):
11            if item in used and start <= used[item]:
12                start = used[item] + 1
13            else:
14                max_len = max(max_len, i - start + 1)
15            used[item] = i
16    
17        return max_len
18        

This blog is under a 知识共享许可协议
本作品采用知识共享署名 4.0 国际许可协议进行许可
本文链接:https://www.xffish.info/articles/2018/11/11/1541942501000.html