LeetCode第438题 Finding All Anagrams in a string(c++)

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,说明两个字符串互为异位词。

上课去了,回来再写。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值