这是一道难度为Easy的问题,但我觉得挺难的。记录一下。
问题
Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
分析
这道题是让我们在字符串s中找字符串p的anagram,anagram的意思是易位构词,字符相同,顺序可以不同。返回所有anagram在s中的开始索引。
思路
可以使用滑动窗口方法解决,只需要遍历一遍字符串s,时间复杂度为O(n)。
定义两个指针right和left。right负责扩展窗口,left负责收缩窗口。窗口大小始终不大于p.length(),不断筛选数据。当窗口大小等于p.length()时,窗口中所有元素正好是p的Anagrams,此时索引left即为一个解。
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) {
return list;
}
int[] hash = new int[256];
for (char c : p.toCharArray()) {
hash[c]++;
}
int left = 0, right = 0, count = 0;
while (right < s.length()) {
if (hash[s.charAt(right)] > 0){
hash[s.charAt(right)]--;
count++;
right++;
} else {
hash[s.charAt(left)]++;
left++;
count--;
}
if (count == p.length()) {
list.add(left);
}
}
return list;
}
}
总结
学习了其他人的解法才做出来的,这种解法比起暴力破解在时间复杂度上有显著提高,但也需要一点想象力。