Skip to content

Latest commit

 

History

History
37 lines (35 loc) · 939 Bytes

3.md

File metadata and controls

37 lines (35 loc) · 939 Bytes

题目地址

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

解答1

def lengthOfLongestSubstring(s):
    """ 无重复子串的长度 """
    st = {}
    i, ans = 0, 0
    for j in range(len(s)):
        if s[j] in st:
            i = st[s[j]] if st[s[j]] > i else i
        ans = ans if ans > j - i + 1 else j - i + 1
        st[s[j]] = j + 1
    return ans

解答2

def lengthOfLongestSubstring(s):
    """ 无重复子串的长度 """
    max_length, temp_length = 0, 0
    test = ''
    for i in s:
        if i not in test:
            test += i
            temp_length += 1
        else:
            if temp_length >= max_length:
                max_length = temp_length
            index = test.find(i)
            test = test[(index + 1):] + i
            temp_length = len(test)
    if temp_length > max_length:
        max_length = temp_length
    return max_length