438. Find All Anagrams in a String
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 1: Array + Sliding Window, Time complexity:O(n), Space complexity:O(26) * */ fun findAnagrams(s: String, p: String): List<Int> { val result = ArrayList<Int>() if (p.length > s.length) { return result } val sMap = IntArray(26) val pMap = IntArray(26) val sLength = s.length val pLength = p.length for (c in p) { pMap[c - 'a']++ } for (i in 0 until sLength) { if (i >= pLength) { //remove the element out of window to keep tracking compare, the length of this window is pLength sMap[s[i - pLength] - 'a']-- } sMap[s[i] - 'a']++ if (sMap contentEquals pMap) { result.add(i + 1 - pLength) } } return result } }