LeetCode 438. Find All Anagrams in a String

Sliding Window (fixed length)

比较straightforward的方法,用长度为p的window去扫描,判断两个hashtable统计结果是否相同。在不清楚C++里unordered_map有没有重载==的情况写,可以用两个vector来做counter。

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> res;
        if (s.size()<p.size()) return res;
        vector<int> sc(256), pc(256); // s count and p count
        for (int i=0;i<p.size();++i){
            ++sc[s[i]];
            ++pc[p[i]];
        }
        if (sc==pc) res.push_back(0);
        for (int i=1;i<=s.size()-p.size();++i){ //all possible start points
            // delete s[i-1], add s[p.size()-1+i]
            --sc[s[i-1]];
            ++sc[s[p.size()-1+i]];
            if (sc==pc) res.push_back(i);
        }
        return res;
    }
};

 

Sliding Window (General)

Sliding Window 模板写法,用一个hashtable记录所需字符的个数,还需要一个count判断窗口中已经有多少p中的字符。

如果count等于t.size(),说明当前窗口的字串包含p里所有的字符了。此时需要额外判断窗口大小是否等于p的size,如果相等,那么start就是一个答案。

参考 LeetCode 76. Minimum Window Substring / 567. Permutation in String / Share Purchases

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        unordered_map<int,int> hash; // number of char needed
        for (char ch:p) ++hash[ch];
        int count=0;
        int start=0;
        vector<int> res;
        for (int i=0;i<s.size();++i){
            if (--hash[s[i]]>=0) ++count;
            while (count==p.size()){
                if (i-start+1==p.size()) 
                    res.push_back(start);
                if (++hash[s[start]]>0) --count;
                ++start;
            }
        }
        return res;
    }
};

 

转载于:https://www.cnblogs.com/hankunyan/p/11588774.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值