[HashTable]003 Longest Substring Without Repeating Characters

  • 分類:HashTable

  • 考察知識點:HashTable String

  • 最優(yōu)解時間復(fù)雜度: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:
                # 找最長的不重復(fù)字符的字符串
                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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評論 0 10
  • 想要找高清的,好看的圖片,這個方法,不可錯過 Saver for 500px.apk 下載地址:百度網(wǎng)盤 500p...
    混混_9368閱讀 390評論 0 0
  • 文/東軍 (1) 這個夏天,很熱,據(jù)說是全球最熱的一個夏天。這個暑假,很忙...
    東軍閱讀 1,156評論 2 2
  • couch potato. Time tries all. Practice makes perfect.
    MEAnnie閱讀 184評論 0 0

友情鏈接更多精彩內(nèi)容