zoukankan      html  css  js  c++  java
  • [LeetCode] 1165. Single-Row Keyboard

    There is a special keyboard with all keys in a single row.

    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|.

    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.

    单行键盘。

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

    我们可以按从左到右的顺序,用一个长度为 26 的字符串 keyboard (索引从 0 开始,到 25 结束)来表示该键盘的键位布局。

    现在需要测试这个键盘是否能够有效工作,那么我们就需要个机械手来测试这个键盘。

    最初的时候,机械手位于左边起第一个键(也就是索引为 0 的键)的上方。当机械手移动到某一字符所在的键位时,就会在终端上输出该字符。

    机械手从索引 i 移动到索引 j 所需要的时间是 |i - j|。

    当前测试需要你使用机械手输出指定的单词 word,请你编写一个函数来计算机械手输出该单词所需的时间。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/single-row-keyboard
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题不涉及算法,是一道实现题。思路请参见代码。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int calculateTime(String keyboard, String word) {
     3         int index = 0;
     4         int count = 0;
     5         for (char c : word.toCharArray()) {
     6             // 当前字母与前一个字母的距离
     7             count += Math.abs(keyboard.indexOf(c) - index);
     8             // 记录当前字母的下标以便下一次的比较
     9             index = keyboard.indexOf(c);
    10         }
    11         return count;
    12     }
    13 }

    LeetCode 题目总结

  • 相关阅读:
    【Gitbook】实用配置及插件介绍
    【Git】学习记录
    【Ubuntu】使用记录
    intellij idea
    【应用】信息短时存储
    leetcode pow(x,n)实现
    SSM框架-----------SpringMVC+Spring+Mybatis框架整合详细教程
    《平凡的世界》之我看
    垃圾收集器与内存分配策略(三)
    垃圾收集器与内存分配策略(二)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14494149.html
Copyright © 2011-2022 走看看