★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:爲敢(WeiGanTechnologies)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rzdmlgxx-kh.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
There is a special keyboard with all keys in a single row.git
Given a string keyboard
of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i
to index j
is |i - j|
.github
You want to type a string word
. Write a function to calculate how much time it takes to type it with one finger. 微信
Example 1:函數
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.
Example 2:佈局
Input: keyboard = "pqrstuvwxyzabcdefghijklmno", word = "leetcode" Output: 73
Constraints:測試
keyboard.length == 26
keyboard
contains each English lowercase letter exactly once in some order.1 <= word.length <= 10^4
word[i]
is an English lowercase letter.咱們定製了一款特殊的力扣鍵盤,全部的鍵都排列在一行上。spa
咱們能夠按從左到右的順序,用一個長度爲 26 的字符串 keyboard
(索引從 0 開始,到 25 結束)來表示該鍵盤的鍵位佈局。code
如今須要測試這個鍵盤是否可以有效工做,那麼咱們就須要個機械手來測試這個鍵盤。htm
最初的時候,機械手位於左邊起第一個鍵(也就是索引爲 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 <= 10^4
word[i]
是一個小寫英文字母1 class Solution { 2 func calculateTime(_ keyboard: String, _ word: String) -> Int { 3 let arr:[Character] = Array(keyboard) 4 var map:[Character:Int] = [Character:Int]() 5 for i in 0..<arr.count 6 { 7 map[arr[i]] = i 8 } 9 var currPos:Int = 0 10 var totalTime:Int = 0 11 for c in word 12 { 13 totalTime += abs(currPos - map[c]!) 14 currPos = map[c]! 15 } 16 return totalTime 17 } 18 }