[leetcode]Longest Substring Without Repeating Characters @ Python


原題地址:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

題意:Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

解題思路:使用一個哈希表,記錄字符的索引。例如對於字符串'zwxyabcabczbb',當檢測到第二個'a'時,由於之前已經有一個'a'了,所以應該從第一個a的下一個字符重新開始測算長度,但是要把第一個a之前的字符在哈希表中對應的值清掉,如果不清掉的話,就會誤以為還存在重復的。比如檢測到第二個'z'時,如果第一個'z'對應的哈希值還在,那就出錯了,所以要把第一個'a'之前的字符的哈希值都重置才行。

代碼:

class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        start = 0
        maxlen = 0
        hashtable = [-1 for i in range(256)]
        for i in range(len(s)):
            if hashtable[ord(s[i])] != -1:
                while start <= hashtable[ord(s[i])]:
                    hashtable[ord(s[start])] = -1
                    start += 1
            if i - start + 1 > maxlen: maxlen = i - start + 1
            hashtable[ord(s[i])] = i
        return maxlen
class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        start = 0
        maxlen = 0
        dict = {}
        for i in range(len(s)):
            dict[s[i]] = -1
        for i in range(len(s)):
            if dict[s[i]] != -1:
                while start <= dict[s[i]]:
                    dict[s[start]] = -1
                    start += 1
            if i - start + 1 > maxlen: maxlen = i - start + 1
            dict[s[i]] = i
        return maxlen

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM