LeetCode 438. Find All Anagrams in a String

来源:互联网 发布:脱口秀大会 知乎 编辑:程序博客网 时间:2024/06/07 04:48

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.

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

三、解题思路

题目难度是Easy,但是做起来却一点都不Easy。意思是找一个子串,这个子串和p比较,长度一样 出现的字符以及每个字符出现的次数都是相同的。问这样的子串有多少个。

Sliding Window

  • 关键点一:像这种找子串的可以使用滑动窗口Sliding Window来做。这个窗口由left和right来约束[left, right]两个闭区间,刚开始只是left=right=0然后left不动,right不断增长,直到达到某个值时,left和right一起增长,这样就实现了窗口的创建和向右滑动。
  • 关键点二:对于p中出现的字符以及个数需要记录下来。可以使用一个数组asciiNums,长度设置为256是因为ascii码一共只有256个,初始化的值表示角标对应的ascii字符在p中出现的次数,那么没有出现过的就是0。之后如果s中出现过该字符,那么数组对应位置的值就减一。如果减之后的值>=0 就说明p中的该字符出现了一次,这时p中未出现的字符数量count就减一。之所以要判断是>=0 是因为如果数组原来的值是0(说明p中没有出现)那么减一后就成了负的,说明这个字符没有在p中 而s中出现了,这种情况下p中剩下未出现的字符count数保持不变。
  • 如果count==0 说明p中的字符全部出现了,找到一个符合条件的子串,left就是子串的首地址。之后要向右移动滑动窗口sliding window.移动方法是left++ right++ left增加后需要将left对应的字符添加到p中(如果p中原来有这个字符)而且也要更新p中未出现字符的个数count
class Solution {public:    vector<int> findAnagrams(string s, string p) {        if(s.size() == 0 || s.size() < p.size()) return vector<int>();        int sL = s.size(), count = p.size(), left = 0, right = 0;        vector<int> ret;        int asciiNums[256] = {0};        for (auto ite : p){            asciiNums[ite]++;//p里面有的字符全部初始化为1 p里面没有的全初始化为0        }        while(right < sL)        {            char ch = s.at(right);            asciiNums[ch]--;            if(asciiNums[ch] >= 0){//说明这个ch原来在p中,否则就被减成负的了                count--;//有一个ch在p中出现,s中现在也出现了,那么未出现的字符总个数就减一            }            if((right - left + 1) == p.size()){                if(count == 0){//p中的字符全部出现过了,bingo 找到一个符合条件的substr                    ret.push_back(left);                }                char ch = s.at(left);                asciiNums[ch]++;                if(asciiNums[ch] > 0)count++;                left++;                right++;            }else{                right++;            }        }        return ret;    }};