1165. Single-Row Keyboard

LeetCode easy original: C# #array #csharp #easy #leetcode #math #matrix #string
题目文本会按所选界面语言从俄语翻译;代码保持不变。

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

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

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

示例:

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# 解法

匹配/原始
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++ 解法

自动草稿,提交前请检查
#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 解法

匹配/原始
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 解法

匹配/原始
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 解法

匹配/原始
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 解法

匹配/原始
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

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

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

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

😎

Vacancies for this task

活跃职位 with overlapping task tags are 已显示.

所有职位
目前还没有活跃职位。