【python学习记录3】Longest Substring Without Repeating Characters

问题描述

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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
        """
        lens = len(s)
        if lens < 2 :
            return lens
        maxlen = 0
        p = 0
        q = 1
        while q < lens :
            if p == q :
                q = q+1
                continue
            if s[q] in s[p:q] :
                p = p + 1
            else :
                q = q + 1
                if (q - p) > maxlen :
                    maxlen = q - p
        if (q - p) > maxlen :
            return q - p
        else :
            return maxlen

经验总结

  • “滑动窗体”的方法,一步一步一逐渐递进窗体边缘
  • python的字符串切片操作

你可能感兴趣的:(【python学习记录3】Longest Substring Without Repeating Characters)