题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
通过全测试用例
思路:
设置当前最长不重复子串的长mx_len,初始化为0;
for循环遍历字符串s,
如果从当前下标开始到前mx_len个字符构成的新子串s[i - mx_len : i + 1]是不重复的子串,则mx_len + 1.
其中不重复子串的判断是用子串长和其转化成set集合后的长度对比:len(str_nw) == len(set(str_nw))
最后,mx_len输出即可
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return int整型
#
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # write code here
        if len(s) == 1:
            return 1
        else:
            mx_len = 0
            for i in range(len(s)):
                str_nw = s[i - mx_len : i + 1]
                if len(str_nw) == len(set(str_nw)):
                    mx_len += 1
            return mx_len
查看15道真题和解析
