Leetcode(3)无重复字符的最长子串
[题目表述]:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
第一种方法:暴力
执行用时:996 ms; 内存消耗:12.9MB 效果:太差
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ Maxsize=0 res='' if len(s)==1:Maxsize=1 for i in range(len(s)): for j in s[i:len(s)]: if j not in res:res+=j else: break Maxsize=max(Maxsize,len(res)) res='' return Maxsize
学习
利用一个空串来存储子串
for对迭代对象的使用
第二种方法:一个for加切片操作
执行用时:60 ms; 内存消耗:12.1MB 效果:非常好
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ res = '' maxlen = 0 for i in s: if i not in res: res += i else: maxlen = max(maxlen, len(res)) index = res.index(i) res = res[index + 1:] + i return max(maxlen, len(res))
学习
算法有点类似于字符串匹配模式算法KMP
出现重复的移动到重复字符的后一个位置,截取之后继续操作
就不用for+for,只需要用一个for,跟改进匹配算法一样的改进方式
字符串可以+= + 这种重载运算符
切片
• [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串• [start:] 从start 提取到结尾
• [:end] 从开头提取到end - 1
• [start:end] 从start 提取到end - 1
• [start🔚step] 从start 提取到end - 1,每step 个字符提取一个
• 左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1
第三种方法:set+滑窗
执行用时:472 ms; 内存消耗:12MB 效果:一般
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 //
学习
采用python的set,可以知道无重复子串的可能最大值,把可能的最大长度作为滑动窗口的初始大小,在搜索中调节大小直到找到。
set集合 set(s)转化成一个集合 每个字符是个单元 无序的不重复元素序列
一开始就知道无重复的有多少个,然后依次减去找,无重复的set
这种算法不能判断len(s)=0 or 1
来源:https://www.cnblogs.com/ymjun/p/11645088.html