TypingDistance
SRM 560 · 2012-06-05 · by meret
Problem Statement
Jakub is trying out a one-dimensional keyboard. It consists of a single row of keys. The distance between any two adjacent keys is 1. Each key contains a distinct letter of the English alphabet. Jakub uses only one finger to type on the keyboard. He wonders what is the smallest total distance he will have to move his finger while typing a given word.
For example, if the keyboard's only row is "qwertyuiop", and Jakub wants to type the word "potter", he will have to move his finger from 'p' to 'o' (distance 1), from 'o' to 't' (distance 4), from 't' to 't' (distance 0), from 't' to 'e' (distance 2) and from 'e' to 'r' (distance 1), for a total distance of 1 + 4 + 0 + 2 + 1 = 8.
You are given a
Notes
- When moving the finger from the i-th key to the j-th key, the distance covered by the move can be computed as |i-j|, that is, the positive difference between i and j.
Constraints
- keyboard will contain between 1 and 26 characters, inclusive.
- Each character in keyboard will be a different lowercase letter of the English alphabet ('a'-'z').
- word will contain between 1 and 50 characters, inclusive.
- Each character in word will be present in keyboard.
"qwertyuiop" "potter" Returns: 8
The example from the problem statement.
"tc" "tctcttccctccccttc" Returns: 9
"a" "aaaaaaaaaaa" Returns: 0
"kwadrutove" "rowerowe" Returns: 39
"qwertyuiopasdfghjklzxcvbnm" "topcodersingleroundmatchgoodluckhavefun" Returns: 322
Submissions are judged against all 55 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class TypingDistance with a public method int minDistance(string keyboard, string word) · 55 test cases · 2 s / 256 MB per case