438. 找到字符串中所有字母异位词
给定两个字符串 s 和 p,找到 s 中所有 p 的异位词的子串,返回这些子串的起始索引。不考虑答案输出的顺序。异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。
题意
在给定字符串中找到与给定字符串的异味词的字串,并返回这些字串的起始索引。
思路
用哈希表存目标串的字符及其个数,用双指针i,j维护一个滑动窗口,每次添加一个字符的时候把对应字符个数–,移出的时候把对应字符个数++,当对应字符个数为0时,把符合条件的字符个数++或–,最后判断符合条件的字符个数是否等于目标字符串的个数
代码
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char,int> hash;
for(auto x : p) hash[x]++;
int cnt = hash.size();
vector<int> res;
for(int i = 0, j = 0, ans = 0; i < s.size(); i++){
if(--hash[s[i]] == 0) ans++;
if(i - j + 1 > p.size()){
if(hash[s[j]] == 0) ans--;
hash[s[j++]]++;
}
if(ans == cnt) res.push_back(j);
}
return res;
}
};
560. 和为 K 的子数组
给你一个整数数组 nums 和一个整数 k ,请你统计并返回该数组中和为 k 的子数组的个数 。子数组是数组中元素的连续非空序列。
题意
求数组中的子数组和为k的子数组的个数
思路
用前缀和求子数组的和,用哈希表维护前缀和出现的个数,注意hash[0] = 1;
代码
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n = nums.size();
int res = 0;
vector<int> s(n + 1);
for(int i = 1; i <= n; i++) s[i] = s[i - 1] + nums[i - 1];
unordered_map<int, int> hash;
hash[0] = 1;
for(int i = 1; i <= n; i++){
res += hash[s[i] - k];
hash[s[i]]++;
}
return res;
}
};