leetcode 41 最长不重复子串 python

leetcode 41 最长不重复子串 python

给定一个数组arr,返回arr的最长无的重复子串的长度(无重复指的是所有数字都不相同)。

#
# 
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
    def maxLength(self , arr ):
        # write code here
        dic={}
        res=tmp=0
        for j in range(len(arr)):
            i=dic.get(arr[j],-1)#通过key返回value值,若key不存在则返回默认值-1
#             print(i)
#             print('----')
            dic[arr[j]]=j#字典key为列表元素,value更新元素最新位置下标
#             print(dic)
            #当出现重复元素时,重复元素的间隔数与之前记录下来的最大间隔数进行比较,否则每循环一次,间隔数+1
            tmp=tmp+1 if tmp<j-i else j-i
#             print(tmp)
#             print('---')
            res=max(res,tmp)
#             print(res)
#             print('--')
        
        return res
while True:
    try:
          
        import sys
        #lines=sys.stdin.readline()
        #lines=[[1,2,3,3,4]]
        #arr=list(map(int,lines.split(']')[0].split('[')[-1].split(',')))
        arr=[1,1,2,3,2,4]
        s=Solution()
        res=s.maxLength(arr)
        print(res)
        break
    except:break

解法2

#
# 
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
    def maxLength(self , arr ):
        # write code here
        l = len(arr)
        a = {}
        maxl = 0
        tmp = 0
        j = -1
        for i in range(l):
            if arr[i] in a and j < a[arr[i]]:
                j = a[arr[i]]
            a[arr[i]] = i
            if (i-j)>maxl:
                maxl = i-j
        return maxl
while True:
    try:
        import sys
        lines=sys.stdin.readline()
        arr=list(map(int, lines.split(']')[0].split('[')[-1].split(',')))
        s=Solution()
        res=s.maxLength(arr)
        print(res)
        
    except:
        break

解法3

class Solution:
    def maxLength(self, s):
        dict={}
        begin=0
        result=0
        word=[]
        for i in range(len(s)):
            if s[i] not in dict or dict[s[i]]==0:
                dict[s[i]]=1
                word.append(s[i])
                result=max(result,len(word))
            else:  
                dict[s[i]]+=1
                while dict[s[i]]>1:
                    dict[s[begin]]-=1
                    begin+=1
                word=[]
                for j in range(begin,i+1):
                    word.append(s[j])
        return result  
while True:
    try:
          
        import sys
        #lines=sys.stdin.readline()
        #lines=[[1,2,3,3,4]]
        #arr=list(map(int,lines.split(']')[0].split('[')[-1].split(',')))
        arr='aabcc'
        s=Solution()
        res=s.maxLength(arr)
        print(res)
        break
    except:break

解法4

class Solution(object):
    def maxLength(self, s):
        """
        :type s: str
        :rtype: int
        """
        max=0
        for i, char1 in enumerate(s):
            temp=s[i]
            for j, char2 in enumerate(s[i+1:]):
                if char2 in temp:
                    break
                else:
                    temp+=char2
            if len(temp)>max:
                max=len(temp)
        return max
while True:
    try:
          
        import sys
        #lines=sys.stdin.readline()
        #lines=[[1,2,3,3,4]]
        #arr=list(map(int,lines.split(']')[0].split('[')[-1].split(',')))
        arr='aabcc'
        s=Solution()
        res=s.maxLength(arr)
        print(res)
        break
    except:break

解法5

class Solution:
    def maxLength(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;
while True:
    try:
          
        import sys
        #lines=sys.stdin.readline()
        #lines=[[1,2,3,3,4]]
        #arr=list(map(int,lines.split(']')[0].split('[')[-1].split(',')))
        arr='aabcc'
        s=Solution()
        res=s.maxLength(arr)
        print(res)
        break
    except:break

解法6

def no_repeat_str(s):
    '''找出来一个字符串中最长不重复子串'''
    res_list = []
    length = len(s)
    for i in range(length):
        tmp = s[i]
        for j in range(i + 1, length):  # 遍历,不存在则拼接,已存在则打断循环
            if s[j] not in tmp:
                tmp += s[j]  
            else:
                break
        res_list.append(tmp)  # 构造子串列表
    # 以下代码目的是取子串列表中长度最大的元素,方法很多,以下是两种思路:
    # 方法一(冒泡排序):
    for i in range(len(res_list) - 1):
        for j in range(len(res_list) - i - 1):
            if len(res_list[j]) > len(res_list[j + 1]):
                res_list[j], res_list[j + 1] = res_list[j + 1], res_list[j]
    """
    # 方法二(选择排序):
    for i in range(len(res_list)):  
        k = i
        j = i + 1
        while j < len(res_list):
            if len(res_list[k]) > len(res_list[j]):
                k = j
            j += 1
        if i != k:
            res_list[i], res_list[k] = res_list[k], res_list[i]
        """

    return res_list[-1]


if __name__ == '__main__':
    str_list = ['5432467843', 'fdsaefkjkgdok', 'jhrd123xfdsa8042d5439']
    for s in str_list:
        res = no_repeat_str(s)
        print('%s最长非重复子串为:%s,长度为: %s' % (s, res, len(res)))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值