1165. Single-Row Keyboard

LeetCode easy original: C# #array #csharp #easy #leetcode #math #matrix #string
Task text is translated from Russian for the selected interface language. Code is left unchanged.

Есть специальная клавиатура, на которой все клавиши расположены в один ряд.

Дана string keyboard длиной 26, указывающая на раскладку клавиатуры (индексирована от 0 до 25). Изначально ваш палец находится на индексе 0. Чтобы напечатать символ, нужно переместить палец на индекс нужного символа. Время, затраченное на перемещение пальца с индекса i на индекс j, равно |i - j|.

Вам нужно напечатать строку word. Напишите функцию для расчета времени, необходимого для её набора одним пальцем.

Example:

Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"

Output: 4

Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.

Total time = 2 + 1 + 1 = 4.

C# solution

matched/original
public class Solution {
    public int CalculateTime(string keyboard, string word) {
        int[] keyIndices = new int[26];
        for (int i = 0; i < keyboard.Length; i++) {
            keyIndices[keyboard[i] - 'a'] = i;
        }
        
        int prev = 0;
        int result = 0;
        
        foreach (char c in word) {
            int index = keyIndices[c - 'a'];
            result += Math.Abs(prev - index);
            prev = index;
        }
        
        return result;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int CalculateTime(string keyboard, string word) {
        vector<int>& keyIndices = new int[26];
        for (int i = 0; i < keyboard.size(); i++) {
            keyIndices[keyboard[i] - 'a'] = i;
        }
        
        int prev = 0;
        int result = 0;
        
        foreach (char c in word) {
            int index = keyIndices[c - 'a'];
            result += abs(prev - index);
            prev = index;
        }
        
        return result;
    }
}

Java solution

matched/original
class Solution {
    public int calculateTime(String keyboard, String word) {
        int[] keyIndices = new int[26];
        for (int i = 0; i < keyboard.length(); i++) {
            keyIndices[keyboard.charAt(i) - 'a'] = i;
        }
        
        int prev = 0;
        int result = 0;
        
        for (char c : word.toCharArray()) {
            int index = keyIndices[c - 'a'];
            result += Math.abs(prev - index);
            prev = index;
        }
        
        return result;
    }
}

JavaScript solution

matched/original
var calculateTime = function(keyboard, word) {
    const keyIndices = new Array(26).fill(-1)
    for (let i = 0; i < keyboard.length; i++) {
        keyIndices[keyboard.charCodeAt(i) - 97] = i
    }
    
    let prev = 0
    let result = 0
    
    for (let c of word) {
        const index = keyIndices[c.charCodeAt(0) - 97]
        result += Math.abs(prev - index)
        prev = index
    }
    
    return result
}

Python solution

matched/original
class Solution:
    def calculateTime(self, keyboard: str, word: str) -> int:
        key_indices = [-1] * 26
        for i, c in enumerate(keyboard):
            key_indices[ord(c) - ord('a')] = i
        
        prev = 0
        result = 0
        
        for c in word:
            index = key_indices[ord(c) - ord('a')]
            result += abs(prev - index)
            prev = index
        
        return result

Go solution

matched/original
func calculateTime(keyboard string, word string) int {
    keyIndices := make([]int, 26)
    for i, c := range keyboard {
        keyIndices[c - 'a'] = i
    }
    
    prev := 0
    result := 0
    
    for _, c := range word {
        index := keyIndices[c - 'a']
        result += abs(prev - index)
        prev = index
    }
    
    return result
}

func abs(a int) int {
    if a < 0 {
        return -a
    }
    return a
}

Algorithm

Клавиатура содержит уникальные строчные английские буквы, поэтому мы можем сопоставить её с arrayом размера 26. Создадим array размера 26, назовём его keyIndices. Сохраните индекс каждой буквы в этом arrayе, проходя по строке keyboard. Инициализируйте переменную result значением 0, которая будет хранить сумму всех расстояний. Объявите переменную prev, которая будет хранить индекс предыдущей клавиши. Поскольку начальная позиция равна 0, инициализируйте её значением 0.

Проходите по строке word буква за буквой. Для каждой буквы c добавьте ∣prev−indexOf(c)∣ к result. Обновите prev до индекса c.

Повторите шаги 6 и 7 для всех букв. В конце прохода result будет содержать итоговое время, необходимое для набора слова.

😎

Vacancies for this task

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.