leetcode 438Find All Anagrams in a String 大概就是尋找異位詞;
阿新 • • 發佈:2019-02-20
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".
題目解釋:意思是尋找異位詞的起始座標的位置;
思路:(滑動視窗+查詢表)
1、構建兩個字典;
vector<int>vs,vp(26,0);不知道為什麼用陣列是錯了 只能用動態陣列;
int vs[26] vp[26]={0};用來存放在 lenp範圍內 某個字元出現的次數;並不需要處理位置的順序;
2、用滑動視窗的思路;從前往後遍歷 滑動視窗的大小應該 size==lenp;
如果left>lenp ;說明滑動視窗的大小超過了 字串p的長度;要進行left++;並且將最左邊的元素去除掉;
然後迴圈將右側的新元素加入到滑動視窗之中:
CODE::
class Solution { public: vector<int> findAnagrams(string s, string p) { vector<int>result; int lens=s.size(); int lenp=p.size(); if(lens==0||p==0) return result; vector<int>vs(26,0); vector<int>vp(26,0);//用陣列出錯了 why? for(char c:p)//遍歷p字串 將結果存入到字典vp中去; vp[c-'a']++; for(int i=0;i<lens;i++)//遍歷s字串;[left,right]為滑動視窗; { if(i>=lenp)//如果當前的索引的值大於等於 字串p的長度;那麼這個i滑動視窗的左邊位置需要去除;left++;左側縮減範圍; vs[s[i-lenp]-'a']--; vs[s[i]-'a']++;//right++;新的元素加入到滑動視窗中; if(vs==vp)//如果兩個陣列相同的話 代表的是 其中所含相同的元素 並且 個數也相同; result.push_back(i-lenp+1);//將滑動視窗的開始索引壓入到動態陣列中去;’ } return result; } };