题解 | #字符串加密#
字符串加密
http://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
import java.util.*; //耗时50min 主要在于集合基本知识不熟练 程序中出了很多错误 public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); while(scan.hasNextLine()){ String key = scan.nextLine(); String resource = scan.nextLine(); //1.将key放入LinkedHashSet去重 Set<Character> set = new LinkedHashSet<>(); for(Character ch : key.toCharArray()){ set.add(ch); } //2.将key从完整字母表集合中删除,并将key和剩余集合组成新集合 Set<Character> alphaBet = new HashSet<>();//完整字母表 char ch1='a'; while(ch1>='a' && ch1<='z'){ alphaBet.add(ch1++); } for(Iterator iterator=alphaBet.iterator();iterator.hasNext();){ char ch2 = (char)iterator.next(); if(set.contains(ch2)) iterator.remove();//删除key包含的字母 } ArrayList<Character> pwList = new ArrayList<>();//新集合 for(Character ch : set){ pwList.add(ch); } for(Character ch : alphaBet){ pwList.add(ch); } //3.将顺序字母表与新集合组成一个map Map<Character,Character> map = new HashMap<>(); char key2='a'; for(Character ch : pwList){ map.put(key2++,ch); } //4.利用map完成加密 StringBuffer buffer = new StringBuffer(); for(Character ch : resource.toCharArray()){ buffer.append(map.get(ch)); } System.out.println(buffer.toString()); } } }