题目链接:https://leetcode-cn.com/problems/minimum-time-to-type-word-using-special-typewriter/
代码:
/* 1974. 使用特殊打字机键入单词的最少时间 */ #include<iostream> #include<string> #include<exception> #include<algorithm> using namespace std; class Solution { private: int min_distance(char current, char target) { if (current == target) { return 0; } int count1 = abs(target - current); int count2 = -abs(target - current) + 26; int result = min(count1, count2); return result; } public: int minTimeToType(string word) { int min_time = 0; char current = 'a'; for (char target : word) { min_time += min_distance(current, target)+1; current = target; } return min_time; } }; int main() { string word; cin >> word; Solution solution; int result = solution.minTimeToType(word); cout << result << endl; return 0; }