题解 | #字符串加密#

字符串加密

https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3

import java.util.*;
import java.io.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String key = br.readLine();
            String target = br.readLine();
            //选用lhm保证输出与输入一致,并且查询与不重复put也快
            LinkedHashMap<Character, Integer> lhm = new LinkedHashMap();
            char[] array1 = key.toCharArray();
            int j = 0, flag = 0;
            for (int i = 0; i < array1.length; i++) {
                if (!lhm.containsKey(array1[i])) {
                    if (flag == 0) {
                        //若上一次出现了重复key,则value继续为上一次value+1
                        // 保证连续不断的加1;
                        lhm.put(array1[i], j++);
                    } else {
                        //若没有出现重复key,则一直保持value++,value即为i
                        // j用于记录,若先出现重复key,又出现不重复key,则继续从j开始
                        j = i;
                        flag = 1;
                        lhm.put(array1[i], i);
                    }

                } else {
                    //设置标志位,但出现重复key,不做任何操作
                    flag = 0;
                }
            }
            int size = lhm.size();
            String str = "abcdefghijklmnopqrstuvwxyz";
            for (int i = 0; i < str.length(); i++) {
                if (!lhm.containsKey(str.charAt(i))) {
                    //将不重复的字母放入map中,value接着加1
                    lhm.put(str.charAt(i), size++);
                }
            }
            StringBuffer stb = new StringBuffer();
            for (int i = 0; i < target.length(); i++) {
                if (target.charAt(i) != ' ') {
                    //从26个字母中拿到索引,该索引作为map的value,找到对应key即可
                    int index = str.indexOf(target.charAt(i));
                    for (Map.Entry<Character, Integer> entry : lhm.entrySet()) {
                        if (index == entry.getValue()) {
                            stb.append(entry.getKey());
                        }
                    }
                } else {
                    stb.append(" ");
                }
            }
            System.out.println(stb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务