Problem: HJ21 简单密码
题目描述
描述
现在有一种密码变换算法。
九键手机键盘上的数字与字母的对应: 1--1, abc--2, def--3, ghi--4, jkl--5, mno--6, pqrs--7, tuv--8 wxyz--9, 0--0,把密码中出现的小写字母都变成九键键盘对应的数字,如:a 变成 2,x 变成 9.
而密码中出现的大写字母则变成小写之后往后移一位,如:X ,先变成小写,再往后移一位,变成了 y ,例外:Z 往后移是 a
数字和其它的符号都不做变换。
数据范围: 输入的字符串长度满足
输入描述:
输入一组密码,长度不超过100个字符。
输出描述:
输出密码变换后的字符串
示例1
输入:
YUANzhi1987
输出:zvbo9441987
解题思路
将条件全列出来
算法流程
- 创建Scanner对象:创建一个Scanner对象in,用于读取用户输入。
- 进入循环:使用while循环,判断是否还有输入行。
- 读取输入行:使用in.nextLine()方法读取一行输入,并将其存储在字符串变量str中。
- 遍历字符串:使用for-each循环遍历字符串str中的每个字符。
- 转换字符:调用transformLowerCase()方法,将字符转换为对应的数字或字母。
- 输出结果:使用System.out.print()方法打印转换后的字符。
- transformLowerCase()方法:根据字符的范围判断字符属于哪个数字或字母,并返回对应的字符串。
代码
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
for (char c : str.toCharArray()) {
System.out.print(transformLowerCase(c));
}
}
}
private static String transformLowerCase(char c) {
if (c >= 'a' && c <= 'c') {
return "2";
} else if (c >= 'd' && c <= 'f') {
return "3";
} else if (c >= 'g' && c <= 'i') {
return "4";
} else if (c >= 'j' && c <= 'l') {
return "5";
} else if (c >= 'm' && c <= 'o') {
return "6";
} else if (c >= 'p' && c <= 's') {
return "7";
} else if (c >= 't' && c <= 'v') {
return "8";
} else if (c >= 'w' && c <= 'z') {
return "9";
} else if (c >= 'A' && c <= 'Y') {
return String.valueOf((char) (c + 33));
} else if (c == 'Z') {
return "a";
} else if (c >= '0' && c <= '9') {
return String.valueOf(c);
} else {
return "";
}
}
}
复杂度
- 时间复杂度:
添加时间复杂度, 示例:
- n是字符串的长度
- 空间复杂度:
添加空间复杂度, 示例:
- 常数存储