LeetCode in Kotlin

1974. Minimum Time to Type Word Using Special Typewriter

Easy

There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.

Each second, you may perform one of the following operations:

Given a string word, return the minimum number of seconds to type out the characters in word.

Example 1:

Input: word = “abc”

Output: 5

Explanation:

The characters are printed as follows:

Example 2:

Input: word = “bza”

Output: 7

Explanation:

The characters are printed as follows:

Example 3:

Input: word = “zjpc”

Output: 34

Explanation:

The characters are printed as follows:

Constraints:

Solution

class Solution {
    fun minTimeToType(word: String): Int {
        var min = 0
        var curr = 'a'
        for (i in 0 until word.length) {
            val diff = curr.code - word[i].code
            curr = word[i]
            min += Math.min(diff + 26, Math.min(Math.abs(diff), 26 - diff))
            min++
        }
        return min
    }
}