1165. Single-Row Keyboard

LeetCode easy original: C# #array #csharp #easy #leetcode #math #matrix #string
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

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

Дана 문자열 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 표시됨.

전체 채용
아직 활성 채용이 없습니다.