package LeetCode_438 /** * 438. Find All Anagrams in a String * https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ * * 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". * */ class Solution { /** * solution: Array+Sliding Window, Time complexity:O(n), Space complexity:O(26) * */ fun findAnagrams(s: String, p: String): List<Int> { val result = ArrayList<Int>() val window = p.length val len = s.length if (window == 0 || len == 0) { return result } if (len < window) { return result } var left = 0 var right = 0 val hash = IntArray(26) val pHasp = IntArray(26) while (right < window) { hash[s[right] - 'a']++ pHasp[p[right] - 'a']++ right++ } //scan remaining len of s while (right <= len) { if (pHasp contentEquals hash) { result.add(left) } /* * keep tracking in window size, * for example: cbaebabacd, * next track: eba=>bab... * */ if (right != len) { hash[s[right] - 'a']++ } right++ hash[s[left++] - 'a']-- } return result } }