To type "b", we need to press "2" twice. To type "?" we need to press "1" thrice. To type "5" we need to press "5" four times. To type "0" we need to press "0" twice.
I hope that it's clear how the keypad is being used.
Now Roy has lot of text messages and they are pretty lengthy. So he devised a mechanical-hand-robot (with only 1 finger) which does the typing job. One drawback of this robot is its typing speed. It takes 1 second for single press of any button. Also it takes 1 second to move from one key to another. The initial position of the hand-robot is at key 1.
So if its supposed to type "hack" it will take 1 second to move from key 1 to key 4 and then 2 seconds to type "h".
Now again 1 second to move from key 4 to key 2 and then 1 second to type "a".
Since "c" is present at the same key as "a" movement time is 0. So it simply takes 3 seconds to type "c".
Finally it moves from key 2 to key 5 in 1 second and then 2 seconds to type "k". So in total it took 1+2+1+1+3+1+2= 11 seconds to type "hack".
Example:
Input: s = "hack"
Output: 11
Approach
C++
#include <bits/stdc++.h>using namespace std;int main(){map<char, pair<int, int>> mp;//1mp['.'] = {1, 1};mp[','] = {1, 2};mp['?'] = {1, 3};mp['!'] = {1, 4};mp['1'] = {1, 5};//2mp['a'] = {2, 1};mp['b'] = {2, 2};mp['c'] = {2, 3};mp['2'] = {2, 4};//3mp['d'] = {3, 1};mp['e'] = {3, 2};mp['f'] = {3, 3};mp['3'] = {3, 4};//4mp['g'] = {4, 1};mp['h'] = {4, 2};mp['i'] = {4, 3};mp['4'] = {4, 4};//5mp['j'] = {5, 1};mp['k'] = {5, 2};mp['l'] = {5, 3};mp['5'] = {5, 4};//6mp['m'] = {6, 1};mp['n'] = {6, 2};mp['o'] = {6, 3};mp['6'] = {6, 4};//7mp['p'] = {7, 1};mp['q'] = {7, 2};mp['r'] = {7, 3};mp['s'] = {7, 4};mp['7'] = {7, 5};//8mp['t'] = {8, 1};mp['u'] = {8, 2};mp['v'] = {8, 3};mp['8'] = {8, 4};//9mp['w'] = {9, 1};mp['x'] = {9, 2};mp['y'] = {9, 3};mp['z'] = {9, 4};mp['9'] = {9, 5};//0mp['_'] = {0, 1};mp['0'] = {0, 2};string s = "hack";int cnt = 0;int n = 1;for (int i = 0; i < s.size(); i++){if (mp[s[i]].first != n){cnt++;n = mp[s[i]].first;cnt += mp[s[i]].second;}else{cnt += mp[s[i]].second;}}cout << cnt << "\n";return 0;}
No comments:
Post a Comment