leetcode_3_ Longest Substring Without Repeating Characters

滑动窗口问题
3.找到无重复子串最大长度。medium
自己思想:
外层循环:逐个字符作为子串开头
内层循环:逐个增加当前子串长度,若出现重复,停止跳出循环,并记录当前子串长度。
循环结束
循环结束
取子串长度最大的长度返回。

答案版本1思想:采用Python的set,可以知道无重复子串的可能的最大长度,把可能的最大长度作为滑动窗口的初始大小,并在搜索中调节窗口大小直到找到最大无重复子串。参考代码如下:

class Solution:
	def lengthOfLongestSubstring(self, s):
   		 """
   		 :type s: str
   		 :rtype: int
   		 """

   		len_s = len(s)
  		if len_s == 0:
      		return 0
   		set_s = set(s)
    	# get the max_size of sild window
   		max_len = len(set_s)
    	max_sub_str = ""
    	while max_len:
        	if max_len == 1:
            	return 1
        	i = 0
        	while i + max_len <= len_s:
            	sub_s = s[i:i + max_len]
            	set_sub = set(sub_s)
            	# if there is no repeat in sub string
            	if len(set_sub) == len(sub_s):
                	max_sub_str = sub_s
                	return(len(list(max_sub_str)))
            	i = i + 1
        	# adjust the size of window
        	max_len = max_len - 1

答案2版本(复杂度O(n)):

class Solution:
	# @return an integer
	def lengthOfLongestSubstring(self, s):
    	start = maxLength = 0
    	usedChar = {}
    	for i in range(len(s)):
        	if s[i] in usedChar and start <= usedChar[s[i]]:
            	start = usedChar[s[i]] + 1
        	else:
            	maxLength = max(maxLength, i - start + 1)

        	usedChar[s[i]] = i

    	return maxLength
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值