码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode练习(Python):哈希表类:第3题:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

时间:2020-04-27 15:45:53      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:solution   dex   pytho   题目   str   substr   longest   and   for   

题目:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
思路:
使用哈希表变得简单了很多,使用暴力法很容易超时。
程序:
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = len(s)
        if length <= 0:
            return 0
        if length == 1:
            return 1
        head = 0
        max_length = 0
        myHashMap = {}
        for index in range(length):
            if s[index] in myHashMap and head <= myHashMap[s[index]]:
                head = myHashMap[s[index]] + 1
            else:
                max_length = max(max_length, index - head + 1)
            myHashMap[s[index]] = index
        return max_length

Leetcode练习(Python):哈希表类:第3题:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

标签:solution   dex   pytho   题目   str   substr   longest   and   for   

原文地址:https://www.cnblogs.com/zhuozige/p/12786638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!