Python version-LeetCode learning: 438. Find all letter dysphoric words in the string

Given a string s and a non-empty string p, find all the substrings of p in s and return the starting index of these substrings. The string contains only lowercase English letters, and the length of the strings s and p are not more than 20100. Description:

Aliphatic words refer to strings with the same letters but different arrangements. The order in which the answers are output is not considered.
Example 1: Input: s: "cbaebabacd" p: "abc"

Output: [0, 6]

Explanation:
The substring whose starting index is equal to 0 is "cba", which is an anagram of "abc".
The substring whose starting index is equal to 6 is "bac", which is an anagram of "abc".

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-all-anagrams-in-a-string

method 1:

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        # 特殊情况判定
        if s =='': return None
        if len(s)<len(p): return None
        # 记录目标字符串中各个字符数量的字典
        record=Counter(p)
        length=len(p)
        win={}  # 记录窗口中各个字符数量的字典
        l=0 # 表示窗口的左界限
        rst=[]
        for r,c in enumerate(s):
            if c not in record:   # 当遇到不需要的字符时
                win.clear()       # 将之前统计的信息全部放弃
                l=r+1             # 从下一位置开始重新统计
            else:
                win[c]=win.get(c,0)+1    # 统计窗口内各种字符出现的次数

                if r-l+1==length:       # 当窗口大小与目标字符串长度一致时
                    if win==record:  # 如果窗口内的各字符数量与目标字符串一致就将left添加到结果中
                        rst.append(l)
                    win[s[l]]-=1     # 移除的字符数量减一
                    l+=1             # left右移
        return rst

 

Guess you like

Origin blog.csdn.net/guyu1003/article/details/107415894