这个题比较简单,水文一篇
Map与Set的使用
一、题目描述 题目链接
二、解题
- 将 key — value (字母 — 数字)放到map中
- 新建StringBuilder,遍历 初始的字符串,遇到 字母,通过map寻找到对应的数字,添加数字;遇到数字,直接添加 ;遇到 “-”,跳过即可;
- 当 StringBuilder 长度为 3 时,添加 “-”
public static void main431(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<Character, Character> map = new HashMap<>();
String s1 = "ABCDEFGHIJKLMNOPQRSTYVWXYZ";
String s2 = "22233344455566677778889999";
char[] chars1 = s1.toCharArray();
char[] chars2 = s2.toCharArray();
for (int i = 0; i < chars1.length; i++) {
map.put(chars1[i], chars2[i]);
}
while(scanner.hasNext()){
int nums = scanner.nextInt();
String[] phones = new String[nums];
for (int i = 0; i < nums; i++) {
phones[i] = scanner.nextLine();
}
TreeSet<String> set = transForm(phones, map);
for (String s : set) {
System.out.println(s);
}
System.out.println();
}
}
public static TreeSet<String> transForm(String[] phones, Map<Character, Character> map){
TreeSet<String> set = new TreeSet<>();
for (String phone : phones) {
StringBuilder stringBuffer = new StringBuilder();
for (int j = 0; j < phone.length(); j++) {
if (stringBuffer.length() == 3) {
stringBuffer.append('-');
}
char ch = phone.charAt(j);
if (ch == '-') {
continue;
}
if (ch >= '0' && ch <= '9') {
stringBuffer.append(ch);
} else {
stringBuffer.append(map.get(ch));
}
}
set.add(stringBuffer.toString());
}
return set;
}
鲁北田园,厚德载物
山东德州
|