LeetCode链接:力扣
题目:
给定两个字符串 s 和 p,找到 s 中所有 p 的 变位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。
变位词 指字母相同,但排列不同的字符串。
示例:
输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的变位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的变位词。
代码:
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int n = s.length(), m = p.length();
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
List<Integer> res = new ArrayList<>();
if(n < m){
return res;
}
for(int i = 0; i < m; ++i){
++cnt1[s.charAt(i) - 'a'];
++cnt2[p.charAt(i) - 'a'];
}
if(Arrays.equals(cnt1, cnt2)){
res.add(0);
}
for(int i = m; i < n; ++i){
++cnt1[s.charAt(i) - 'a'];
--cnt1[s.charAt(i - m) - 'a'];
if(Arrays.equals(cnt2, cnt1)){
res.add(i - m + 1);
}
}
return res;
}
}