求字符串不重复子串的最大长度

求字符串不重复子串的最大长度

2 min read

问题描述

Given a string, find the length of the longest substring without repeating characters.
Example:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3.

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

解题思路

对字符串进行一次遍历,每遍历一个字符求一次最大字串长度。

Python实现

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # 保存最大字串长度
        res = 0
        # 保存窗口起始位置
        start = 0
        for idx,ch in enumerate(s):
            # 判断当前字符是否在窗口内
            if ch in s[start:idx]:
                # 若当前字符在窗口内,更新起始位置
                start = s[start:idx].index(ch) + start + 1
            else:
                # 若当前字符不在窗口内,更新最大字串长度
                res = max(res,idx+1-start)
        return res

前一篇

将图片格式转成EPS格式

后一篇

链表数字相加问题