题解
手机
1 条题解
-
0
1. 解题思路
**核心方法:**先建立字符到按键次数的表,再遍历整行,把每个字符对应次数累加。
2. 坑点和注意事项
- pqrs和wxyz各有4个字母,空格需要按1次;getline保留句子中的空格。总按键数≤800,int足够。
/* 思路:先建立字符到按键次数的表,再遍历整行,把每个字符对应次数累加。 关键规则与坑点:pqrs和wxyz各有4个字母,空格需要按1次;getline保留句子中的空格。总按键数≤800,int足够。 时间复杂度:O(L)。空间复杂度:O(L)。 */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; getline(cin, s); string groups[] = {" ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; int cost[256] = {}; for (int j = 0; j < 9; j++) { for (int i = 0; i < (int)groups[j].size(); i++) { // 先建立字符到按键次数的表,再遍历整行,把每个字符对应次数累加。 cost[(unsigned char)groups[j][i]] = i + 1; } } int ans = 0; for (int i = 0; i < (int)s.size(); i++) { ans += cost[(unsigned char)s[i]]; } cout << ans << "\n"; }3. 复杂度
- **时间复杂度:**O(L)。
- **空间复杂度:**O(L)。
- 1