【leetcode系列】【py3】【中等】无重复字符的最长子串
题目:
原题链接: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
解题思路:
添加临时字符串,保存当前的无重复字符的字符串
添加变量,保存当前已有的最大无重复字符子串的长度
对原始字符串进行遍历,并判断当前遍历的字符,在临时字符串中是否存在
- 如果不存在,则追加到临时字符串后面,继续遍历
- 如果存在,则判断是否更新子串最大长度,并将临时字符串的首字符,更新为首个重复字符的下一位,再将当前字符追加到临时字符串后
代码实现:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
tmp_str, max_len = '', 0
for curr_s in s:
if curr_s not in tmp_str:
tmp_str += curr_s
continue
max_len = max(max_len, len(tmp_str))
tmp_str = tmp_str[tmp_str.find(curr_s) + 1:]
tmp_str += curr_smax_len = max(max_len, len(tmp_str))
return max_len