Problem: 438. 找到字符串中所有字母异位词
文章目录
思路 & 解题方法
主要需要注意s长度可能比p短
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( 26 n ) O(26n) O(26n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
Code
python
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
count_s, count_p = [0] * 26, [0] * 26
len_s, len_p = len(s), len(p)
if len_s < len_p:
return []
for ch in p:
count_p[ord(ch) - ord('a')] += 1
for i in range(len_p):
count_s[ord(s[i]) - ord('a')] += 1
left, right = 0, len_p - 1
ans = []
if count_p == count_s:
ans.append(left)
while right < len_s -1:
count_s[ord(s[left]) - ord('a')] -= 1
count_s[ord(s[right + 1]) - ord('a')] += 1
left += 1
right += 1
if count_p == count_s:
ans.append(left)
return ans