问题描述:
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.
The order of output does not matter.
思路一:简单粗暴,一个个找
代码一:
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < p.length(); i++){
if(map.containsKey(p.charAt(i))){
int tmp = map.get(p.charAt(i));
map.replace(p.charAt(i), ++tmp);
}else
map.put(p.charAt(i), 1);
}
for(int i = 0; i <= s.length() - p.length(); i++){
HashMap<Character, Integer> tmpMap = new HashMap<>();
for(int j = i; j < p.length()+i; j++){
if(!tmpMap.containsKey(s.charAt(j))){
tmpMap.put(s.charAt(j), 1);
}
else{
int tmp = tmpMap.get(s.charAt(j));
tmpMap.replace(s.charAt(j), ++tmp);
}
}
if(tmpMap.equals(map))
result.add(i);
}
return result;
}
}
但是:报错!!!Time Limit Exceeded!
去网上搜了一下,发现求子序列的题目一般都用sliding window进行。可以用两个变量left和right代表滑动串口的左右边界,count表示字符串p的大小。首先遍历要寻找的子字符串,将每个字符出现的个数写入数组。然后将左边界和右边界置0,开始进行搜索:
- 如果右边界所指字符存在于子字符串中,则count–。即需要的字符串个数减一;
- 如果count为0,则正好搜索到所需要的字符串个数,将第一个字符的索引加入结果list中;
- 如果此时右边界减左边界为子字符串的长度,此时相当于多一个字符串,所以要删掉左边这个。如果要删掉的这个在字符串中,则需要count加一;如果不在,则count不需要动。
代码:
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
int[] chars = new int[26];
if(s == null || p == null || s.length() < p.length())
return result;
for(char c : p.toCharArray())
chars[c - 'a']++;
int left = 0, right = 0, count = p.length();
while(right < s.length()){
if(--chars[s.charAt(right++) - 'a'] >= 0)
count--;
if(count == 0)
result.add(left);
if(right - left == p.length() && chars[s.charAt(left++) - 'a']++ >= 0)
count++;
}
return result;
}
}