1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public List<Integer> findAnagrams(String s, String p) { if (s == null || s.length() == 0 || s.length() < p.length()) { return new ArrayList<>(); } List<Integer> list = new ArrayList<>(); int[] pArr = new int[26]; int[] sArr = new int[26]; for (int i = 0; i < p.length(); i++) { pArr[p.charAt(i) - 'a']++; sArr[s.charAt(i) - 'a']++; } int i = 0, j = p.length(); while (j < s.length()) { if (isSame(pArr, sArr)) { list.add(i); } sArr[s.charAt(i) - 'a']--; i++; sArr[s.charAt(j) - 'a']++; j++; } if (isSame(pArr, sArr)) { list.add(i); } return list; }
private boolean isSame(int[] arr1, int[] arr2) { for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } }
|