原题链接:找到字符串中所有字母异位词
题目:给定两个字符串 s 和
p
,找到s
中所有p的 异位词,返回这些子串的起始索引
滑动窗口解决:
- 在字符串s中,以字符串p的长度为滑动窗口的长度
- 定义两个数组sCount[]、pCount[]保存字符串s和p中字符的个数
- 添加滑动窗口到数组s中:
- 遍历字符串p和字符串s前p.length()的字符,分别将个数加入sCount[]、pCount[]数组中
- 比较两数组sCount[]、pCount[]是否相同。若相同则说明当前窗口组成的字符串是字符串p的异位词
- 遍历字符串s,同时删除当前窗口的第一个字符以及加入窗口的下一个字符
- 比较两数组sCount[]、pCount[]是否相同。若相同则说明当前窗口组成的字符串是字符串p的异位词
代码:
public List<Integer> findAnagrams(String s, String p) {
if (s.length() < p.length()) return new ArrayList<Integer>();
List<Integer> list = new ArrayList<Integer>();
int[] sCount = new int[26]; //分别保存字符串s中每个字符的个数
int[] pCount = new int[26]; //分别保存字符串p中每个字符的个数
for (int i = 0; i < p.length(); ++i) {
sCount[s.charAt(i) - 'a']++;
pCount[p.charAt(i) - 'a']++;
}
if (Arrays.equals(sCount, pCount)) list.add(0); //当前窗口组成的字符串为字符串p的异位词
for (int i = 0; i < s.length() - p.length(); ++i) { //窗口右移一位
sCount[s.charAt(i) - 'a']--; //删除当前窗口的第一个字符
sCount[s.charAt(i + p.length()) - 'a']++; //增加当前窗口的下一个字符
if (Arrays.equals(sCount, pCount)) list.add(i + 1);
}
return list;
}
总结:
- 使用长度为26的数组统计字符串中每个字符的个数
- 如果两个数组相同,则说明两字符串字符相同(字符位置不一定相同)