1165. Single-Row Keyboard

LeetCode easy original: C# #array #csharp #easy #leetcode #math #matrix #string
Văn bản bài toán được dịch từ tiếng Nga theo ngôn ngữ giao diện. Mã không thay đổi.

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

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

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

Ví dụ:

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# lời giải

đã khớp/gố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++ lời giải

bản nháp tự động, xem lại trước khi gửi
#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 lời giải

đã khớp/gốc
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 lời giải

đã khớp/gốc
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 lời giải

đã khớp/gốc
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 lời giải

đã khớp/gốc
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

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

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

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

😎

Vacancies for this task

việc làm đang hoạt động with overlapping task tags are đã hiển thị.

Tất cả việc làm
Chưa có việc làm đang hoạt động.