题解 | #找到字符串中的异位词#
找到字符串中的异位词
https://www.nowcoder.com/practice/9ff491c910e5427fab6ae67745929085
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param p string字符串
* @return int整型ArrayList
*/
public ArrayList<Integer> findWord (String s, String p) {
// write code here
if(s.length()<p.length()){ // s长度比p短,情况不存在
return null;
}
int[] counts=new int[26]; //记录p中所有字母出现的个数
ArrayList<Integer> res = new ArrayList<>();
for(int i=0;i<p.length();i++){
counts[p.charAt(i)-'a'] += 1;
counts[s.charAt(i)-'a']-=1; /
}
if(araAllZero(counts)){//数组中字母个数是否全为0
res.add(0);
}
for(int j=p.length();j<s.length();j++){
counts[s.charAt(j)-'a']-=1;
counts[s.charAt(j-p.length())-'a']+=1;
if(araAllZero(counts)){
res.add(j-p.length()+1);
}
}
return res;
}
public boolean araAllZero(int[] counts){
for(int count:counts){
if(count!=0)
return false;
}
return true;
}
}

