本文共 1237 字,大约阅读时间需要 4 分钟。
这道题去年用java写过一次,回头看感觉不堪入目,哈哈,这次用python再做一遍
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"Output: 3Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
这道题一开始想想以为是动态规划,但是仔细一想不满足动态规划的无后效性的原则,即我如何达到当前状态的历史信息会影响我下一判断的决策
解这道题就遍历一遍字符串,然后用一个字符串保存之前的迭代的不重叠子串(我用begin和end来替换开一个字符串保存,用这种方式运行会快几ms,从76ms->68ms)和记录长度,如果当前字符在保存的子串中有
说明现在保存的字串已经达到了它的最大不重叠长度,然后比较它的长度是否大于我们之前保存的最大长度,更新最大长度
然后将不重叠子串更新一下,更新为从上一个重叠字符的下一个字符开始到现在迭代的字符(因为我们只需要将上一个重叠的字符去掉之后,它又变成了一个不重叠的字符串)。迭代结束就出结果了。
更多leetcode算法题解法请关注我的专栏或关注我
欢迎大家一起套路一起刷题一起ac
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if s=='': return 0 maxlen,begin,end=1,0,0 for k in range(1,len(s)): index=s.find(s[k],begin,end+1) if index!=-1: maxlen=max(maxlen,end-begin+1) begin=index+1 end+=1 return max(maxlen,end-begin+1)
转载地址:http://oqmrb.baihongyu.com/