1. 程式人生 > >leetcode-438-Find All Anagrams in a String

leetcode-438-Find All Anagrams in a String

IT -- 新的 iss HA nag cpp mat strings

題目描述:

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

要完成的函數:

vector<int> findAnagrams(string s, string p)

說明:

1、給定一個字符串s和非空字符串p,將p中元素不斷交換形成一個新的字符串,如果這個新的字符串在s中能找到匹配的,那麽就輸出匹配到的開始的位置,直到處理到字符串s結束。

2、這道題目難道要記住p經過交換可能形成的所有字符串嗎,難道再類似於滑動窗口一般不斷在s中比較?

其實不用記住所有字符串,記住p經過交換可能形成的所有字符串其實等價於記住p中所有字母出現的次數。

所以代碼如下:

    vector<int> findAnagrams(string s, string p) 
    {
        vector<int>res;
        vector
<int>p1(26,0); vector<int>s1(26,0); for(int i=0;i<p.size();i++) { p1[p[i]-a]++; } for(int i=0;i<p.size();i++) { s1[s[i]-a]++; } if(s.size()<p.size()) return res; if(p1==s1) res.push_back(0); for(int i=1;i<=s.size()-p.size();i++) { s1[s[i-1]-a]--;//當窗口滑動時,s1中要減去窗口前一位的字母1次 s1[s[i-1+p.size()]-a]++;//s1要加上窗口最後新的一維的字母1次 if(s1==p1) res.push_back(i); } return res; }

上述代碼實測35ms,beats 90.84% of cpp submissions。

leetcode-438-Find All Anagrams in a String