LeetCode 438. 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.spa

The order of output does not matter.code

Example 1:blog

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

 

這道題要求統計原字符串中,與模板字符串構成Anagrams的子串有多少,所謂Anagrams,也就是在尋找pattern的一個全排列,可是這裏不用這麼麻煩,只須要統計patter中各個字母的出現次數,以後逐步滑動,判斷原字符串中與子串等長的字符串個字母出現的次數,patter和源字符串統計結果相等,那就說明該位置匹配string

 1 class Solution {
 2 public:
 3     vector<int> findAnagrams(string s, string p) {
 4         vector<int> sv(26, 0), pv(26, 0), res;
 5         if (s.size() < p.size())
 6             return res;
 7         for (int i =  0; i < p.size(); i++)
 8         {
 9             pv[p[i]-'a']++;
10             sv[s[i]-'a']++;
11         }
12         if (sv == pv)
13             res.push_back(0);
14         for (int i = p.size(); i < s.size(); i++)
15         {
16             sv[s[i]-'a']++;
17             sv[s[i-p.size()]-'a']--;
18             if (pv == sv)
19                 res.push_back(i - p.size() + 1);
20         }
21         return res;
22     }
23 };

固然也能夠作一些優化思路:it

 1 class Solution {
 2 public:
 3     vector<int> findAnagrams(string s, string p) {
 4         if (s.empty()) return {};
 5         vector<int> res, m(256, 0);
 6         int left = 0, right = 0, cnt = p.size(), n = s.size();
 7         for (char c : p) ++m[c];
 8         while (right < n) {
 9             if (m[s[right++]]-- >= 1) --cnt;
10             if (cnt == 0) res.push_back(left);
11             if (right - left == p.size() && m[s[left++]]++ >= 0) ++cnt;
12         }
13         return res;
14     }
15 };

這種方法只須要遍歷一遍而且不須要比較兩個向量的大小io

相關文章
相關標籤/搜索