[HashTable]003 Longest Substring Without Repeating Characters

  • 分类:HashTable

  • 考察知识点:HashTable String

  • 最优解时间复杂度:O(n)

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example2:

Input: "pwwkew"
Output: 3
Explanation: 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.

代码:

解法:

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:

        length = 0

        if s==None or s=="":
            return length

        start = 0
        char_dict = dict()
        for end in range(len(s)):
            if s[end] in char_dict:
                # 找最长的不重复字符的字符串
                start = max(start, char_dict[s[end]]+1)
            char_dict[s[end]] = end
            # 找这些字符串里最大的
            length = max(length, end-start+1)
        
        return length

讨论:

1.看到Without repeatedly啥的,记得用Hash Table,在Python中就是dictionary
2.j是新的一段的开头,一定要记住** j=max(j,d[n]+1)**,不能让它回到前面去

WechatIMG1626.jpeg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 想要找高清的,好看的图片,这个方法,不可错过 Saver for 500px.apk 下载地址:百度网盘 500p...
    混混_9368阅读 311评论 0 0
  • 文/东军 (1) 这个夏天,很热,据说是全球最热的一个夏天。这个暑假,很忙...
    东军阅读 1,108评论 2 2
  • couch potato. Time tries all. Practice makes perfect.
    MEAnnie阅读 157评论 0 0