簡體   English   中英

如何以更有效的方式搜索最長的子字符串?

[英]How can I search for longest substring in a more efficient way?

我正在嘗試在線性時間內搜索字符串中最長的子字符串。 如何在不使用 max 函數的情況下執行此操作?

這是問題:

給定一個字符串,找出沒有重復字符的最長子字符串的長度。 你能在線性時間內找到解決方案嗎?

這是我的解決方案:

class Solution:
  def lengthOfLongestSubstring(self, sentence):

     evid = []
     word = ''

     for i in sentence:
      if i not in word:
        word += i
      else:
        evid.append(word)
        word = ''
        word += i

     return len(max(evid, key=len))

print(Solution().lengthOfLongestSubstring('abrkaabcdefghijjxxx'))

謝謝!

在進行成員資格測試 ( O(N) ) 時,您不應該對字符串進行操作。 真正的線性解決方案將使用一個set和兩個指針:

class Solution:
    def lengthOfLongestSubstring(self, sentence):
        crnt = set()
        m = lo = hi = 0
        
        while hi < len(s):
            if (c := s[hi]) in crnt:  # membership check is O(1)
                # move lo past the most recent occurrence of c
                while (d := s[lo]) != c:
                    # removing all characters along the way
                    crnt.remove(d)
                    lo += 1
                lo += 1
            else:
                crnt.add(c)
                if len(crnt) > m:
                    m = len(crnt)
            hi += 1
        
        return m

由於每個索引/字符最多被添加到crnt集或從crnt集中刪除一次,並且兩個操作和包含檢查都為O(1) ,因此這種方法是線性的。

使用sliding window並避免在 OP 請求時使用max想法相同。 試試這個看看是否有幫助?

 def lengthOfLongestSubstring(self, s: str) -> int:
           
     maxSubLen = 0
     start = 0
     seen = {}
     for i in range(len(s)):
         c = s[i]
         if c in seen and start <= seen[c]:
            start = seen[c] + 1
         else:
             if maxSubLen > (i-start +1):
                maxSubLen = maxSubLen
             else:
                 maxSubLen = i - start + 1
                 #maxSubLen = max(maxSubLen, i - start + 1) # no max! 
         seen[c] = i
                
    return maxSubLen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM