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".
题目大意:给一个字符串s和一个非空字符串p,在s中找到所有p的Anagrams【由颠倒字母顺序而构成的字[短语]】
解题目思路:
这题我一开始是这样想的,建一个set把p对应的所有Anagrams全部丢进这个set里面【这是一件大活】,然后再把s中所有的子串给遍历一遍每当set里面有对应的字符串和子串对应上了那么就把对应的下标记录下来,由于这个想法过于淳朴,就舍弃了;
本人又去查找资料,发现有个高端做法,建一个对应的散列表hash,hash[i]记录的是字符i在串p里面出现的次数,然后构建两个指针left、right,都只能单向移动,再建造一个类似与标志位的count来记录当前right和left之间包含的字符中拥有的p中的字符。
代码如下:
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return list;
int[] hash = new int[256]; //character hash
for (char c : p.toCharArray()) {
hash[c]++;
}
int left = 0, right = 0, count = p.length();
while (right < s.length()) {
if (hash[s.charAt(right++)]-- >= 1) count--;
if (count == 0) list.add(left);
if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++;
}
return list;
}
参考资料:https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/;