python經典算法題:無重復字符的最長子串


題目:無重復字符的最長子串。

給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。

示例 1:

輸入: “abcabcbb”
輸出: 3
解釋: 因為無重復字符的最長子串是 “abc”,所以其長度為 3。
示例 2:

輸入: “bbbbb”
輸出: 1
解釋: 因為無重復字符的最長子串是 “b”,所以其長度為 1。
示例 3:

輸入: “pwwkew”
輸出: 3
解釋: 因為無重復字符的最長子串是 “wke”,所以其長度為 3。
請注意,你的答案必須是 子串 的長度,“pwke” 是一個子序列,不是子串。

解法1:常規思路(本人做的)
class Count:
    def __init__(self):
        self.curLength = 0

    def compare(self, temp: str):
        lens = len(set(temp))
        if lens != len(temp):
            return False
        else:
            self.curLength = lens
            return True

    def circulation(self, s: str):
        flag = False
        length_s = len(s)  # 8
        temp = ""
        j = 0
        while j + self.curLength < length_s:  # 1+0<8
            temp = s[j:j + self.curLength + 1]  # temp = "a"
            if self.compare(temp):  # tem不重復
                continue
            else:
                j += 1
        return self.curLength
解法2:神仙思路(網上看的)
class Solution:
    def lengthOfLongestSubstring(self, s):
        """ :type s: str :rtype: int """
        st = {}
        i, ans = 0, 0
        for j in range(len(s)):
            if s[j] in st:
                i = max(st[s[j]], i)
            ans = max(ans, j - i + 1)
            st[s[j]] = j + 1
        return ans


免責聲明!

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



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