LeetCode in Kotlin

3361. Shift Distance Between Two Strings

Medium

You are given two strings s and t of the same length, and two integer arrays nextCost and previousCost.

In one operation, you can pick any index i of s, and perform either one of the following actions:

The shift distance is the minimum total cost of operations required to transform s into t.

Return the shift distance from s to t.

Example 1:

Input: s = “abab”, t = “baba”, nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Output: 2

Explanation:

Example 2:

Input: s = “leet”, t = “code”, nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

Output: 31

Explanation:

Constraints:

Solution

import kotlin.math.min

class Solution {
    fun shiftDistance(s: String, t: String, nextCost: IntArray, previousCost: IntArray): Long {
        val costs = Array<LongArray?>(26) { LongArray(26) }
        var cost: Long
        for (i in 0..25) {
            cost = nextCost[i].toLong()
            var j = if (i == 25) 0 else i + 1
            while (j != i) {
                costs[i]!![j] = cost
                cost += nextCost[j].toLong()
                if (j == 25) {
                    j = -1
                }
                j++
            }
        }
        for (i in 0..25) {
            cost = previousCost[i].toLong()
            var j = if (i == 0) 25 else i - 1
            while (j != i) {
                costs[i]!![j] = min(costs[i]!![j].toDouble(), cost.toDouble()).toLong()
                cost += previousCost[j].toLong()
                if (j == 0) {
                    j = 26
                }
                j--
            }
        }
        val n = s.length
        var ans: Long = 0
        for (i in 0..<n) {
            ans += costs[s[i].code - 'a'.code]!![t[i].code - 'a'.code]
        }
        return ans
    }
}