sliding window 编程范式python

滑动窗口(Sliding Window)问题经常使用快慢指针(slow, fast pointer)

  1. [0, slow) 的区域为滑动窗口已经探索过的区域
  2. [slow, fast]的区域为滑动窗口正在探索的区域
  3. (fast, end of array)为待探索的区域

 Sliding Window的问题主要分为:

  • fixed size sliding window
  • dynamic size sliding window

 先来看看fixed size sliding window相关的问题

1.Strstr:
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Input: haystack = "hello", needle = "ll"
Output: 2



class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle == '':
            return 0
        l = len(needle)
        for i in range(len(haystack)-len(needle)+1):
            if haystack[i:i+l] == needle:
                return i
                break
        return -1

 2.Repeated DNA Sequennce
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
Return:
["AAAAACCCCC", "CCCCCAAAAA"]

class Solution(object):
    def findRepeatedDnaSequences(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        seen, repeated = set(), set()
        for i in range(len(s)-9):
            t = s[i:i+10]
            if t in seen:
                repeated.add(t)
            seen.add(t)
        return list(repeated)

接下来看看Non-fixed Size Sliding-Window的例子:

Longest Substring Without Repeating Characters

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {}
        maxLen = 0
        start = 0
        for i,c in enumerate(s):
            if c not in d or d[c] < start:
                maxLen = max(maxLen, 1+i-start)
            else:
                start = d[c] + 1
            d[c] = i
        return maxLen

注意到start的变化

Longest Palindromic Substring

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)==0:
        	return 0
        maxLen=1
        start=0
        for i in xrange(len(s)):
        	if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
        		start=i-maxLen-1
        		maxLen+=2
        		continue

        	if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
        		start=i-maxLen
        		maxLen+=1
        return s[start:start+maxLen]

 

你可能感兴趣的:(算法思维,python)