题解 | #简单密码#
简单密码
https://www.nowcoder.com/practice/7960b5038a2142a18e27e4c733855dac
package NewComer; import java.util.HashMap; import java.util.Scanner; import java.util.Map; import java.util.Set; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class HJ21_简单密码 { private static Map<String,String> map = new HashMap<>(); static{ //静态初始化、加载map容器 map.put("1","1"); map.put("abc","2"); map.put("def","3"); map.put("ghi","4"); map.put("jkl","5"); map.put("mno","6"); map.put("pqrs","7"); map.put("tuv","8"); map.put("wxyz","9"); map.put("0","0"); } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s1 = in.nextLine(); char c1[] = s1.toCharArray(); //转传承char型数组 StringBuffer sb = new StringBuffer(); //Map stringMap = new HashMap(); for(char c : c1){ if(c>'1' && c<='9'){ sb.append(String.valueOf(c)); //如果是数字就保持不变 } else if(c>='A' && c<='Y'){ char newchar = (char)(c+32+1); //字符串大小写技巧 sb.append(String.valueOf(newchar)); } else if(c == 'Z'){ sb.append('a'); } else{ //最后一种情况,做映射,即去除map容器中的key与字符进行校验并加密 Set<String> keys = map.keySet(); //keySet()函数用于获得map集合里的key值集合。 for(String k:keys){ if(k.contains(String.valueOf(c))){ //查看keys集合中有没有输入的字符 sb.append(String.valueOf(map.get(k))); //通过k得到想要映射的结果 } } } } System.out.print(sb); } }