力扣面试题二Python

一、滑动窗口

1.无重复字符的最长子串

给定一个字符串 s ,请你找出其中不含有重复字符的 最长 子串 的长度。

滑动窗口 right left:

用一个哈希集合来维护当前窗口内的字符,确保没有重复

右指针right不断向右移动,将新字符加入窗口

如果新字符已经在窗口,移动左指针left,直到窗口内不再有重复字符

每次移动后,都计算当前窗口的长度,并更新最长长度记录

遍历相关

  • 需要使用索引, for right in range(len(s))

使用场景: 滑动窗口、双指针、需要修改元字符串中的字符、需要根据索引做字符判断

  • 当只需要字符本身时,直接遍历for char in s

使用场景:统计字符频率、单纯对每个字符做转换或判断、不需要索引的简单遍历

  • 两者结合用enumerate 同时返回索引和对应的值
python 复制代码
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
       
        char_set=set()
        left=0
        max_len=0
       
        for right in range(len(s)):
            # 如果当前字符已在窗口中,移动左指针直到移除重复字符
            while s[right] in char_set:
                char_set.remove(s[left])
                left+=1
            char_set.add(s[right])
            # 更新最长子串长度 比较之前记录的最大子串,和当前
            max_len=max(max_len,right-left+1)
        return max_len

2.找到字符串中所有字母异位词

给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

滑动窗口+字符频率统计

在s上维护一个长度为len(p)的滑动窗口,统计窗口内的字符频率

每次窗口滑动时,更新频率表,和p的频率表做对比,相当于记录起始索引

  • 初始化字符频率数组

p_count=[0]*26

s_count=[0]*26

(1)两个长度为26的数组分别统计p和s窗口内的字符频率,

(2)每个位置对应一个小写字母 0对应a,1对应b

  • 统计p和s初始窗口的字符频率

ord() python内置函数,作用是返回单个字符对应的Unicode【全球统一的字符编码标准】编码值

与之对应的chr() 根据Uniocde编码值返回对应的字符

p_count[ord(p[i])-ord('a')]+=1 或者- 97 把小写字母转换为0-25的数字索引

python 复制代码
class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        s_len, p_len = len(s), len(p)
        
        if s_len < p_len:
            return []

        ans = []
        s_count = [0] * 26
        p_count = [0] * 26
        for i in range(p_len):
            s_count[ord(s[i]) - 97] += 1
            p_count[ord(p[i]) - 97] += 1

        # 检查初始窗口是否匹配
        if s_count == p_count:
            ans.append(0)

        for i in range(s_len - p_len):
            # 移出窗口最左边的字符
            s_count[ord(s[i]) - 97] -= 1
            # 加入窗口最右侧的新字符
            s_count[ord(s[i + p_len]) - 97] += 1
            # 检查当前窗口是否匹配
            if s_count == p_count:
                ans.append(i + 1)

        return ans

二、子串

1.和为k的子数组

给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。 子数组是数组中元素的连续非空序列

子串:

定义pre_sum[i] :数组前i个元素的和 i从1开始

子数组 num[j...i]的和为: pre_sum[i]-pre_sum[j-1]

pre_num[i]=原数组前i个元素的和 --->nums[0]+nums[1]+...+nums[i-1]

pre_sum[j-1]=原数组前j-1个元素的和 --->nums[0]+nums[1]+...+nums[j-2]

相减后,刚好消去前j-1个元素,只剩目标子数组

和等于k,即pre_sum[i]-pre_sum[j-1]=k 从下标j-1到下标i-1的子数组和 num[j...i]

哈希表核心表现形式是字典 {'a':1} {0:1}

使用哈希表count_map来记录每个前缀和出现的次数,遍历数组时,计算当前前缀和current_sum,然后去哈希表里找current_sum-k出现了几次

python 复制代码
class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
     
        count_map={0:1} # 初始的前缀和0,出现1次
        current_sum=0
        result=0
        for num in nums:
            current_sum+=num
            # 检查是否存在前缀和等于current_sum-k
            if (current_sum-k)in count_map:
                result+=count_map[current_sum-k]
            # 更新当前前缀和的出现次数
            count_map[current_sum]=count_map.get(current_sum,0)+1
        return result  
相关推荐
ZPC82105 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82105 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David5 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱5 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone5 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩5 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
QQ4022054965 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再5 小时前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082855 小时前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884755 小时前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask