Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
Constraints:
1 <= s.length, p.length <= 3 * 104
s and p consist of lowercase English letters.来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目大意:
这道题就是要你找出异位词的所引。
实现思路:
因为异位词是不限定字符顺序的,所以可以利用滑动窗口,统计每一个窗口内各个字符出现的次数。
实现代码:
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int slen=s.length();
int plen=p.length();
int i=0,j=0;
vector<int> nums;
vector<int> s_count(27);
vector<int> p_count(27);
if(slen<plen) return nums;
for(i=0;i<plen;i++){
s_count[s[i]-'a']++;
p_count[p[i]-'a']++;
}
if(s_count==p_count) nums.push_back(0);
for(;i<slen;i++){
s_count[s[i-plen]-'a']--;
s_count[s[i]-'a']++;
if(s_count==p_count) nums.push_back(i-plen+1);
}
return nums;
}
};
通过这道题,我学到了以下几点:
1、首先自然是滑动窗口这种解题思路。
2、其次便在于vector这种容器可以直接用"=="进行比较,比较方便。
并且在官方答案中vector是用emplace_back()函数,目前我还不了解它和push_back()的区别,有机会去了解一下。
3、这道题需要注意的是:题目没有规定string s的长度一定长于string p的长度,所以要在开始的时候对它们的长度进行特判,否则会在第一个循环处出现越界的情况。
接下来,我看到官方答案还进行了优化。
在我的方法中每次都要做两个vector的比较,时间效率是比较慢的,为了避免这样的情况。
我们都可以把两个词频表合成一个,即一个字符串往词频里面加次数,另一个字符串往词频里面减次数,再加一个变量记录词频差异数,如果差异数为 0,说明两个字符串互为异位词。
上课去了,回来再写。