Kotlin solution


  • 0
    S

    This solution is similar to some others, but written in Kotlin

    class Solution {
        fun findAnagrams(s: String, p: String): List<Int> {
            // diff represents difference between sliding window and p
            val diff = IntArray(26)
            for (letter in p) {
                diff[letter - 'a'] += 1
            }
            // sum is the number of letters in p not accounted for in sliding window
            var sum = p.length
            val res = mutableListOf<Int>()
            // letter is the rightmost letter of the sliding window
            for ((index, letter) in s.withIndex()) {
                if (diff[letter - 'a'] > 0) {
                    sum -= 1
                }
                diff[letter - 'a'] -= 1
                if (index >= p.length) {
                    val oldLetter = s[index - p.length]
                    diff[oldLetter - 'a'] += 1
                    if (diff[oldLetter - 'a'] > 0) {
                        sum += 1
                    }
                }
                if (sum == 0) {
                    res.add(index - p.length + 1)
                }
            }
            return res
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.