438. 找到字符串中所有字母异位词
难度:中等
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明:
- 字母异位词指字母相同,但排列不同的字符串。
- 不考虑答案输出的顺序。
示例 1:
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
示例 2:
输入:
s: "abab" p: "ab"
输出:
[0, 1, 2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
解答:
class Solution {
//滑动窗口
//时间复杂度O(N),空间复杂度O(1)
public List<Integer> findAnagrams(String s, String p) {
List<Integer> ans = new ArrayList<>();
if(s == null || s.length() == 0) return ans;
int[] needs = new int[26];
int[] window = new int[26];
int left = 0, right = 0, total = p.length();
for(char ch : p.toCharArray()) needs[ch - 'a']++;
while(right < s.length()){
char chR = s.charAt(right);
if(needs[chR - 'a'] > 0){
window[chR - 'a']++;
if(window[chR - 'a'] <= needs[chR - 'a']) total--;
}
while(total == 0){
if(right - left + 1 == p.length()) ans.add(left);
char chL = s.charAt(left);
if(needs[chL - 'a'] > 0){
window[chL - 'a']--;
if(window[chL - 'a'] < needs[chL - 'a']) total++;
}
left++;
}
right++;
}
return ans;
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/path-sum-iii/solution/qian-zhui-he-di-gui-hui-su-by-shi-huo-de-xia-tian/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。