leetcode 438[easy]---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".
Seen this question in a real interview before? No
思路:给出一个较长的string S 和一个较短的string P,看p的顺序打乱后的所有可能的字符串在s中能不能找到,找得到就把所有找到的开始的位置记录下来。。
学习一种思维模式,先构建两个dict,将相同长度的S和P(P的长度)分别导入两个dict中,value对应字母出现的次数。(想了很久才想清楚原code为什么要有这几步,因为S 和P的长度不一样,用这几步奠定dict的长度,并在以后的步骤中保持住,为比较S和P提供基础保证。)
用while循环比较,(“if sdic==pdic”是否在dict中,只要key:value相同,就代表两个dict相同,不用考虑key出现的顺序),删除掉已经出现过的字母,保证两个dic的key的数量相同。