Leetcode<Longest Substring Without Repeating Characters>

Posted on 2019-06-19 17:00  思思0303  阅读(114)  评论(0)    收藏  举报

被这个解决方案惊艳到。

Longest Substring Without Repeating Characters

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: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        curlen = maxlen = 0 # curlen saves the max len of substrings ending with current num
        for i, num in enumerate(s):
            curlen -= s[i-curlen:i].find(num)
            maxlen = max(maxlen, curlen)
        return maxlen

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3