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; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/438
類似題目:
參考資料:
https://leetcode.com/problems/find-all-anagrams-in-a-string/