1 条题解
-
0
【深基6.习1】手机
解题思路
为 26 个字母建立按键次数表,空格计 1 次。用 getline 读完整行,累加每个字符的成本。
正确性说明
每个字母在其键上的位置决定按键数,每个字符所需次数固定,相加得到完整句子的总次数。
易错点
pqrs 与 wxyz 有四个字母,s 和 z 各需四次;空格也算一次。
复杂度
时间 O(L),空间 O(L)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int cost[] = {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4}; string s; getline(cin, s); int ans = 0; for (char c : s) ans += c == ' ' ? 1 : cost[c - 'a']; cout << ans << "\n"; return 0; }
- 1