LeetCode无重复字符的最长子串

2019-08-02  本文已影响0人  _一杯凉白开

题目要求:

首尝试解题思路

此时可解答出来,但时间复杂度为n的3次方,超过了时间限制,哭。。。

def len_str(s):
    counter = []
    for i in range(len(s)):
        if i == 0:
            counter.append(1)
        elif s[i] in s[:i]:
            temp = s[i]
            cnt = 0
            for j in s[:i+1]:
                if j == temp:
                    cnt += 1
            counter.append(cnt)
        elif s[i] not in s[:i]:
            counter.append(1)  
#    print(counter, len(counter))
    left = 0
    right = 0
    if len(s) == 0:
        res = 0
    else:
        res = 1
    while right < len(s) and left < len(s):
        # 滑动窗口并判断窗口内总和是否等于 right-left+1
        sum_RL = 0
        if right == left and right < len(s):
            sum_RL = counter[right]
        else:
            for i in range(left, right + 1):
                sum_RL += counter[i]
        if sum_RL == right - left + 1:
            res = max(res, right-left+1)
            right += 1
        else:
            for i in range(left+1, len(s)):
                if s[i] == s[left]:
                    counter[i] -= 1
            left += 1
        
#        print('s[right]', 'right', 'left', 'counter[i]')
#        print(res)
    return res

LeetCode通过的思路

def len_str(s):
    left = 0
    right = 0
    if len(s) == 0:
        res = 0
    else:
        res = 1
    while right+1 < len(s) and left < len(s):
        # 滑动窗口并判断下个字符是否出现在窗口内
        right += 1
        cnt = 0
        while left <= right:
            if s[right] in s[left:right]:
                left += 1
                print(s[right], left)
            if s[right] not in s[left:right]:
                break
        print(right, left)
        res = max(res, right - left + 1)
                
    return res
上一篇 下一篇

猜你喜欢

热点阅读