【easy】438.Find All Anagrams in a String 找出字符串中全部的變位詞

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".

這個題用到hash和滑動窗口。
如下轉載,https://www.cnblogs.com/grandyang/p/6014408.html 原博真的是棒棒噠:
這道題給了咱們兩個字符串s和p,讓咱們在s中找字符串p的全部變位次的位置,所謂變位次就是字符種類個數均相同可是順序能夠不一樣的兩個詞,
那麼咱們確定首先就要統計字符串p中字符出現的次數,
而後從s的開頭開始,每次找p字符串長度個字符,來驗證字符個數是否相同,若是不相同出現了直接break,
若是一直都相同了,則將起始位置加入結果res中,參見代碼以下:
class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        if (s.empty()) return {};
        vector<int> res, cnt(128, 0);
        int ns = s.size(), np = p.size(), i = 0;
        for (char c : p) ++cnt[c];
        while (i < ns) {
            bool success = true;
            vector<int> tmp = cnt;
            for (int j = i; j < i + np; ++j) {
                if (--tmp[s[j]] < 0) {
                    success = false;
                    break;
                }
            }
            if (success) {
                res.push_back(i); 
            }
            ++i;
        }
        return res;
    }
};

 

咱們能夠將上述代碼寫的更加簡潔一些,用兩個哈希表,分別記錄p的字符個數,和s中前p字符串長度的字符個數,而後比較,若是二者相同,則將0加入結果res中,而後開始遍歷s中剩餘的字符,每次右邊加入一個新的字符,而後去掉左邊的一箇舊的字符,每次再比較兩個哈希表是否相同便可,參見代碼以下:html

 解法二:spa

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        if (s.empty()) return {};
        vector<int> res, m1(256, 0), m2(256, 0);
        for (int i = 0; i < p.size(); ++i) {
            ++m1[s[i]]; ++m2[p[i]];
        }
        if (m1 == m2) res.push_back(0);
        for (int i = p.size(); i < s.size(); ++i) {
            ++m1[s[i]]; 
            --m1[s[i - p.size()]];
            if (m1 == m2) res.push_back(i - p.size() + 1);
        }
        return res;
    }
};

 

下面這種利用滑動窗口Sliding Window的方法也比較巧妙,首先統計字符串p的字符個數,而後用兩個變量left和right表示滑動窗口的左右邊界,用變量cnt表示字符串p中須要匹配的字符個數,而後開始循環,若是右邊界的字符已經在哈希表中了,說明該字符在p中有出現,則cnt自減1,而後哈希表中該字符個數自減1,右邊界自加1,若是此時cnt減爲0了,說明p中的字符都匹配上了,那麼將此時左邊界加入結果res中。若是此時right和left的差爲p的長度,說明此時應該去掉最左邊的一個字符,咱們看若是該字符在哈希表中的個數大於等於0,說明該字符是p中的字符,爲啥呢,由於上面咱們有讓每一個字符自減1,若是不是p中的字符,那麼在哈希表中個數應該爲0,自減1後就爲-1,因此這樣就知道該字符是否屬於p,若是咱們去掉了屬於p的一個字符,cnt自增1,參見代碼以下:code

解法三:htm

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        if (s.empty()) return {};
        vector<int> res, m(256, 0);
        int left = 0, right = 0, cnt = p.size(), n = s.size();
        for (char c : p) ++m[c];
        while (right < n) {
            if (m[s[right++]]-- >= 1) --cnt;
            if (cnt == 0) res.push_back(left);
            if (right - left == p.size() && m[s[left++]]++ >= 0) ++cnt;
        }
        return res;
    }
};
相關文章
相關標籤/搜索