Skip to content

Latest commit

 

History

History
139 lines (106 loc) · 3.42 KB

File metadata and controls

139 lines (106 loc) · 3.42 KB

English Version

题目描述

我们定制了一款特殊的键盘,所有的键都 排列在一行上 。

给定一个长度为 26 的字符串 keyboard ,来表示键盘的布局(索引从 025 )。一开始,你的手指在索引 0 处。要输入一个字符,你必须把你的手指移动到所需字符的索引处。手指从索引 i 移动到索引 j 所需要的时间是 |i - j|

您需要输入一个字符串 word 。写一个函数来计算用一个手指输入需要多少时间。

 

示例 1:

输入:keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
输出:4
解释:从 0 号键移动到 2 号键来输出 'c',又移动到 1 号键来输出 'b',接着移动到 0 号键来输出 'a'。
总用时 = 2 + 1 + 1 = 4. 

示例 2:

输入:keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode"
输出:73

 

提示:

  • keyboard.length == 26
  • keyboard 按某种特定顺序排列,并包含每个小写英文字母一次。
  • 1 <= word.length <= 104
  • word[i] 为小写英文字母

解法

哈希表实现。

Python3

class Solution:
    def calculateTime(self, keyboard: str, word: str) -> int:
        index = {c: i for i, c in enumerate(keyboard)}
        res = t = 0
        for c in word:
            res += abs(index[c] - t)
            t = index[c]
        return res

Java

class Solution {
    public int calculateTime(String keyboard, String word) {
        Map<Character, Integer> index = new HashMap<>();
        for (int i = 0; i < keyboard.length(); ++i) {
            index.put(keyboard.charAt(i), i);
        }
        int res = 0, t = 0;
        for (char c : word.toCharArray()) {
            res += Math.abs(index.get(c) - t);
            t = index.get(c);
        }
        return res;
    }
}

C++

class Solution {
public:
    int calculateTime(string keyboard, string word) {
        unordered_map<char, int> index;
        for (int i = 0; i < keyboard.size(); ++i) {
            index[keyboard[i]] = i;
        }
        int res = 0, t = 0;
        for (char c : word) {
            res += abs(index[c] - t);
            t = index[c];
        }
        return res;
    }
};

Go

func calculateTime(keyboard string, word string) int {
	index := map[byte]int{}
	for i := 0; i < len(keyboard); i++ {
		index[keyboard[i]] = i
	}
	res := 0
	t := 0
	for i := 0; i < len(word); i++ {
		res += abs(index[word[i]] - t)
		t = index[word[i]]
	}
	return res
}

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

...