Single-Row Keyboard in python

PythonServer Side ProgrammingProgramming

Suppose, there is a special keyboard with all keys in a single row. So if we have a string of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially our finger is at index 0. To type a character, we have to move your finger to the index of the next character. The time taken to move your finger from index i to index j is denoted as |i - j|. So if we want to type a string. we have to define a function to calculate how much time it takes to type it with one finger. So if the input sequences are “abcdefghijklmnopqrstuvwxyz” and the word is “hello”, then the output will be 20, as from a to h, it will be 7, then h to e is 3, then e to l is 7, then l to l is 0, and l to o is 3, so the total is 7 + 3 + 7 + 3 = 20

To solve this, we will follow these steps −

  • Create one map called d, and z := 0
  • for i in range 0 to length of keyboard format string k
    • d[k[i]] := i
  • ans := 0
  • for each character i in word −
    • ans := ans + |d[i] – z|
    • z := d[i]
  • return ans

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def calculateTime(self, k, w):
      d = {}
      z = 0
      for i in range(len(k)):
         d[k[i]]=i
      ans= 0
      for i in w:
         ans += abs(d[i]-z)
         z = d[i]
      return ans
ob1 = Solution()
print(ob1.calculateTime("abcdefghijklmnopqrstuvwxyz", "hello"))

Input

"abcdefghijklmnopqrstuvwxyz"
"hello"

Output

20
raja
Published on 27-Feb-2020 12:01:38
Advertisements