[LeetCode] Find All Anagrams in a String 找出字串中所有的變位詞
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
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".
這道題給了我們兩個字串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中剩餘的字元,每次右邊加入一個新的字元,然後去掉左邊的一箇舊的字元,每次再比較兩個雜湊表是否相同即可,參見程式碼如下:
解法二:
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,參見程式碼如下:
解法三:
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; } };
類似題目:
參考資料: