題目地址:
https://leetcode.com/problems/single-row-keyboard/
給定一個字符串含個英文小寫字母,想象其爲鍵盤,起初手指在位置(也就是鍵盤的第一個字符處),再給定一個單詞,問要打出這個單詞,手指總共要移動多少步。假設手指需要一步一步的在鍵盤上移動。直接用哈希表記錄每個字符所在位置,然後遍歷單詞即可。代碼如下:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int calculateTime(String keyboard, String word) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < keyboard.length(); i++) {
map.put(keyboard.charAt(i), i);
}
int res = map.get(word.charAt(0));
for (int i = 0; i < word.length() - 1; i++) {
res += Math.abs(map.get(word.charAt(i + 1)) - map.get(word.charAt(i)));
}
return res;
}
}
時間複雜度,空間。