There is a special typewriter with lowercase English letters 'a'
to 'z'
arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'
.
Each second, you may perform one of the following operations
1. Move the pointer one character counterclockwise or clockwise.
2. Type the character the pointer is currently on.
Given a string word, return the minimum number of seconds to type out the characters in a word.
Example 1:
Input: word = "abc"
Output: 5
Explanation:
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
Example 2:
Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
Approach
Java
public class MinTimeToTypeWord {public static void main(String[] args) {String word = "bza";System.out.println(minTimeToType(word));}static int minTimeToType(String word) {int totalTime = 0;// initially start character is 'a'int start = 'a';// iterate through whole stringfor (int i = 0; i < word.length(); i++) {// check for which direction we need to goint clockDir = Math.abs((word.charAt(i) - 'a') -(start - 'a'));// update the clockdir as min of clockwise and// anti clockwiseclockDir = Math.min(clockDir, 26 - clockDir);// add clockDir value to final result +1 for type//that charactertotalTime += clockDir + 1;// update the start character as current characterstart = word.charAt(i);}return totalTime;}}
C++
#include <bits/stdc++.h>using namespace std;int minTimeToType(string word){int totalTime = 0;//initially start character is 'a'int start = 'a';//itearate through whole stringfor (int i = 0; i < word.size(); i++){//check for which direction we need to goint clockDir = abs((word[i] - 'a') - (start - 'a'));//update the clockdir as min of clockwise and//anticlockwiseclockDir = min(clockDir, 26 - clockDir);//add clockDir value to final result +1 for//type that charactertotalTime += clockDir + 1;//update the start character as current characterstart = word[i];}return totalTime;}int main(){string word = "bza";cout << minTimeToType(word) << "\n";return 0;}
No comments:
Post a Comment