438. 找到字符串中所有字母异位词
题目链接 | 438. 找到字符串中所有字母异位词 |
---|---|
思路 | 滑动窗口 |
题解链接 | 官方题解 |
关键点 | 顺序比较;判断的状态量可以依此变更时应当使用“滑动窗口”的方式进行更新 |
时间复杂度 | |
空间复杂度 |
代码实现:
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: s_len = len(s) p_len = len(p) if s_len < p_len: return [] answer = [] s_count = [0] * 26 p_count = [0] * 26 a_ord = ord('a') for i in range(p_len): s_count[ord(s[i]) - a_ord] += 1 p_count[ord(p[i]) - a_ord] += 1 if s_count == p_count: answer.append(0) for i in range(s_len - p_len): s_count[ord(s[i]) - a_ord] -= 1 s_count[ord(s[i+p_len]) - a_ord] += 1 if s_count == p_count: answer.append(i+1) return answer
python-优化版本的滑动窗口
思路:维护“差异量” 时间复杂度:由class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: s_len = len(s) p_len = len(p) if s_len < p_len: return [] answer = [] a_ord = ord('a') ch_diff_count = [0] * 26 for i in range(p_len): ch_diff_count[ord(s[i]) - a_ord] += 1 ch_diff_count[ord(p[i]) - a_ord] -= 1 diff = sum([ item != 0 for item in ch_diff_count ]) if diff == 0: answer.append(0) for i in range(s_len - p_len): index = ord(s[i]) - a_ord if ch_diff_count[index] == 1: diff -= 1 elif ch_diff_count[index] == 0: diff += 1 ch_diff_count[index] -= 1 index = ord(s[i+p_len]) - a_ord if ch_diff_count[index] == -1: diff -= 1 elif ch_diff_count[index] == 0: diff += 1 ch_diff_count[index] += 1 if diff == 0: answer.append(i+1) return answer
分类:
LeetCode
标签:
LeetCode-滑动窗口
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效