解题思路
-
字符转换规则:
- 小写字母:根据九键键盘映射转换为对应数字
- 大写字母:先转为小写,再后移一位,即
转换为
,
转换为
,
转换为
,
,
转换为
,
转换为
。
- 数字和其他字符:保持不变
-
具体实现:
- 遍历字符串,根据不同字符类型进行相应转换
算法及复杂度
- 算法:字符串处理
- 时间复杂度:
,其中
是输入字符串的长度
- 空间复杂度:
注意事项
-
九键键盘映射:
- abc -> 2
- def -> 3
- ghi -> 4
- jkl -> 5
- mno -> 6
- pqrs -> 7
- tuv -> 8
- wxyz -> 9
-
大写字母处理:
- 先转为小写
- 向后移动一位(Z转为a)
-
其他字符:
- 数字保持不变
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
while (cin >> str) {
for (int i = 0; i < str.size(); i++) {
// 小写字母转换为数字
if (str[i] >= 'a' && str[i] <= 'c') str[i] = '2';
if (str[i] >= 'd' && str[i] <= 'f') str[i] = '3';
if (str[i] >= 'g' && str[i] <= 'i') str[i] = '4';
if (str[i] >= 'j' && str[i] <= 'l') str[i] = '5';
if (str[i] >= 'm' && str[i] <= 'o') str[i] = '6';
if (str[i] >= 'p' && str[i] <= 's') str[i] = '7';
if (str[i] >= 't' && str[i] <= 'v') str[i] = '8';
if (str[i] >= 'w' && str[i] <= 'z') str[i] = '9';
// 大写字母转换
if (str[i] == 'Z') str[i] = 'a';
if (str[i] >= 'A' && str[i] <= 'Y') {
str[i] = tolower(str[i]) + 1;
}
}
cout << str << endl;
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] str = sc.next().toCharArray();
for (int i = 0; i < str.length; i++) {
// 小写字母转换为数字
if (str[i] >= 'a' && str[i] <= 'c') str[i] = '2';
if (str[i] >= 'd' && str[i] <= 'f') str[i] = '3';
if (str[i] >= 'g' && str[i] <= 'i') str[i] = '4';
if (str[i] >= 'j' && str[i] <= 'l') str[i] = '5';
if (str[i] >= 'm' && str[i] <= 'o') str[i] = '6';
if (str[i] >= 'p' && str[i] <= 's') str[i] = '7';
if (str[i] >= 't' && str[i] <= 'v') str[i] = '8';
if (str[i] >= 'w' && str[i] <= 'z') str[i] = '9';
// 大写字母转换
if (str[i] == 'Z') str[i] = 'a';
if (str[i] >= 'A' && str[i] <= 'Y') {
str[i] = (char)(Character.toLowerCase(str[i]) + 1);
}
}
System.out.println(new String(str));
}
sc.close();
}
}
s = list(input().strip())
for i in range(len(s)):
# 小写字母转换为数字
if 'a' <= s[i] <= 'c': s[i] = '2'
if 'd' <= s[i] <= 'f': s[i] = '3'
if 'g' <= s[i] <= 'i': s[i] = '4'
if 'j' <= s[i] <= 'l': s[i] = '5'
if 'm' <= s[i] <= 'o': s[i] = '6'
if 'p' <= s[i] <= 's': s[i] = '7'
if 't' <= s[i] <= 'v': s[i] = '8'
if 'w' <= s[i] <= 'z': s[i] = '9'
# 大写字母转换
if s[i] == 'Z': s[i] = 'a'
if 'A' <= s[i] <= 'Y':
s[i] = chr(ord(s[i].lower()) + 1)
print(''.join(s))
算法及复杂度
- 算法:字符串处理
- 时间复杂度:
,其中
是输入字符串的长度
- 空间复杂度: