牛客[编程题] HJ29 字符串加解密

发布时间 2023-11-09 13:21:55作者: 张德长
HJ29 字符串加解密
中等  通过率:25.47%  时间限制:1秒  空间限制:32M
 

描述

对输入的字符串进行加解密,并输出。

加密方法为:

当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;

当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;

其他字符不做变化。

解密方法为加密的逆过程。
数据范围:输入的两个字符串长度满足 1 \le n \le 1000 \ ,保证输入的字符串都是只由大小写字母或者数字组成

输入描述:

第一行输入一串要加密的密码
第二行输入一串加过密的密码

输出描述:

第一行输出加密后的字符
第二行输出解密后的字符

示例1

输入:
abcdefg
BCDEFGH
输出:
BCDEFGH
abcdefg

 

using System.Collections.Generic;
using System;

public class Program {
    public static void Main() {
        string line;
        string line1 = null;
        string line2 = null;
        while ((line = System.Console.ReadLine ()) !=
                null) { // 注意 while 处理多个 case
            if (line1 == null)
                line1 = line;
            else {
                line2 = line;
                var map = GetEncodeMap();
                string encode = "";
                string decode = "";
                for (int i = 0; i < line1.Length; i++) {
                    encode += Encode(line1[i], map).ToString();
                }
                for (int i = 0; i < line2.Length; i++) {
                    decode += Decode(line2[i], map).ToString();
                }
                Console.WriteLine(encode);
                Console.WriteLine(decode);
            }

        }
    }
    public static char Encode(char c, Dictionary<char, char> map) {
        foreach (var kv in map) {
            if (kv.Key == c)return kv.Value;
        }
        return c;
    }
    public static char Decode(char c, Dictionary<char, char> map) {
        foreach (var kv in map) {
            if (kv.Value == c)return kv.Key;
        }
        return c;
    }
    public static Dictionary<char, char> GetEncodeMap() {
        int dis = 'a' - 'A';
        Dictionary<char, char> dic = new  Dictionary<char, char> ();
        for (int i = 'A'; i < 'Z'; i++) {
            dic.Add((char)i, (char)(i + 1 + dis));
        }
        dic.Add('Z', 'a');
        for (int i = 'a'; i < 'z'; i++) {
            dic.Add((char)i, (char)(i + 1 - dis));
        }
        dic.Add('z', 'A');
        for (int i = '0'; i < '9'; i++) {
            dic.Add((char)i, (char)(i + 1));
        }
        dic.Add('9', '0');
        return dic;
    }
}