這是一道難度爲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;
}
}
總結
學習了其他人的解法才做出來的,這種解法比起暴力破解在時間複雜度上有顯著提高,但也需要一點想象力。