题解 | #字符串加密#

字符串加密

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

import java.util.Scanner;
import java.util.LinkedHashSet;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String rule = scanner.nextLine();
        String content = scanner.nextLine();

        // 将加密规则添加到set中
        LinkedHashSet<Character> set = new LinkedHashSet<>();
        for (char c : rule.toCharArray()) {
            set.add(c);
        }
        // 按照顺序补全剩余字母
        char start = 'a';
        while (set.size() != 26) {
            if (!set.contains(start)) {
                // set中不包含该字母,添加该字母并移向下一位
                set.add(start);
                start++;
            } else {
                // set中包含该字母,直接移向下一位
                start++;
            }
        }
        // 遍历需要加密的字符串
        char startLetter = 'a';
        int startIndex = 1;
        int[] contents = new int[content.length()];
        int index = 0;
        for (char c : content.toCharArray()) {
            int len = (int) c - startLetter;
            int letterIndex = startIndex + len;
            contents[index++] = letterIndex;
        }
        // 通过运算得到字符串字母在加密字母表中的位置
        for (int i : contents) {
            int indexInSide = 1;
            for (Character c : set) {
                if (i == indexInSide) {
                    System.out.print(c);
                    break;
                }
                indexInSide++;
            }
        }
    }
}

全部评论

相关推荐

牛客78099800...:实习现在还不捞26届的啊,我投了很多,没有进流程的,以为是在搞秋招,但意外发现大三的不少都面实习了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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