publicclassSolution{booleanisContains(int[] nums){for(int num : nums){if(0!= num)returnfalse;}returntrue;}publicList<Integer>findAnagrams(String s,String p){List<Integer> result =newArrayList<>();int[] nums =newint[26];if(s.length()< p.length())return result;for(int i =0; i < p.length(); i++){
nums[s.charAt(i)-'a']++;
nums[p.charAt(i)-'a']--;}if(isContains(nums)){
result.add(0);}for(int i = p.length(); i < s.length(); i++){
nums[s.charAt(i)-'a']++;
nums[s.charAt(i - p.length())-'a']--;if(isContains(nums)){
result.add(i - p.length()+1);}}return result;}}
Go代码
funcfindAnagrams(s string, p string)(result []int){iflen(s)<len(p){return}
nums :=make([]int,26)for i :=0; i <len(p); i++{
nums[p[i]-'a']--
nums[s[i]-'a']++}ifcontains(nums){
result =append(result,0)}
offset :=len(p)for i :=len(p); i <len(s); i++{
oldCh, newCh := s[i-offset], s[i]
nums[oldCh-'a']--
nums[newCh-'a']++ifcontains(nums){
result =append(result, i-offset+1)}}return}funccontains(nums []int)bool{for i :=0; i <len(nums); i++{if0!= nums[i]{returnfalse}}returntrue}