题解 | #字符串加密#

字符串加密

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

import java.util.Scanner;
import java.util.Arrays;
import java.util.LinkedList;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
  	// a-z的字母表
    public static final LinkedList<String> WORD_LIST = new LinkedList<>
    (Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
                   "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"));


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String key = in.nextLine();
        String word = in.nextLine();
        LinkedList<String> newTable = rebuildTable(key);
        System.out.println(encode(word, newTable));
    }

    private static String encode(String str, LinkedList<String> newTable) {
        int len = str.length();
        // 计算出每个字母在a-z这个字母表中的位置
        LinkedList<Integer> location = new LinkedList<>();
        for (int i = 0; i < len; i++) {
            int charStr = (int) str.charAt(i);
            // 因为条件上说了输入的都是小写字母
            location.add(charStr - 97);
        }
        StringBuilder stringBuilder = new StringBuilder();
        // 从新的字母表中按原来的位置去取新字母
        location.forEach(l -> stringBuilder.append(newTable.get(l)));
        return stringBuilder.toString();
    }

  	// 用key来重新建立字母表
    public static LinkedList<String> rebuildTable(String key) {
        LinkedList<String> rdKeyList = new LinkedList<>();
        for (int i = 0, len = key.length(); i < len; i++) {
            String k = key.charAt(i) + "";
            if (!rdKeyList.contains(k)) {
                rdKeyList.add(k);
                WORD_LIST.remove(k);
            }
        }
        rdKeyList.addAll(WORD_LIST);
        return rdKeyList;
    }
}

全部评论

相关推荐

05-16 11:16
已编辑
东华理工大学 Java
牛客73769814...:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
牛客创作赏金赛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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