LeetCode-3.无重复字符的最长子串——初见双指针

题目: 无重复字符的最长子串

LeetCode-3.无重复字符的最长子串——初见双指针_第1张图片

思路:

双指针题

  1. 指针q永远步进一步,指针p不动,直到p/q两个指针指向的字符一样;
  2. 当q指针指向的内容,和p~q之间的内容有重复时:
    2.1 返回p/q之间的位差,即当前的无重复子串长度
    2.2 再找到和q指针当前指向的字符一样的字符在p~q中的位置,将p指针指向其下一个位置;对于q而言还是步进,和普通无异
  3. 当q指针到达字符串末尾的时候循环截止

code

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s) <= 1:
            return len(s)
        p,q = 0,1
        max_len = 1
        while q < len(s):
            pos = s[p:q].find(s[q])
            if pos != -1:  # 只有没找到才会返回-1
                max_len = max(max_len, q - p)
                p += pos + 1
            q += 1
        max_len = max(max_len, q - p)
        return max_len

你可能感兴趣的:(LeetCode,Python,#双指针)