题解 | #字符串加解密#

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

该问题主要考虑解法就是定义字典,分别是加密字典和解密字典;

分别定义一个加密方法,一个解密算法;对加密内容使用加密字典进行逐个字符转换,针对解密方法,对传入的字符串逐个使用解密字典进行解密;

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        run();
    }
//    加密字典
    private static Map<Character,Character> encryptionDictionary = new HashMap<>();
//    解密字典
    private static Map<Character,Character> decryptDictionary = new HashMap<>();
    static {
//        小写
        char charLowerStart = 'a';
        char charLowerEnd = 'z';
        char numLowerStart = '0';
//        大写
        char charUpperStart = 'A';
        char charUpperEnd = 'Z';
        for (int i = 0; i < 25; i++) {
            encryptionDictionary.put((char)(charLowerStart+i),(char)(charUpperStart+i+1));
        }
        for (int i = 0; i < 25; i++) {
            encryptionDictionary.put((char)(charUpperStart+i),(char)(charLowerStart+i+1));
        }
        encryptionDictionary.put(charLowerEnd,charUpperStart);
        encryptionDictionary.put(charUpperEnd,charLowerStart);
        for (int i = 0; i < 9; i++) {
            encryptionDictionary.put((char)(numLowerStart+i),(char)(numLowerStart+i+1));
        }
        encryptionDictionary.put('9','0');
        for (Map.Entry<Character, Character> characterCharacterEntry : encryptionDictionary.entrySet()) {
            decryptDictionary.put(characterCharacterEntry.getValue(),characterCharacterEntry.getKey());
        }

    }
    private static void run() {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str1 = in.nextLine();
        String str2 = in.nextLine();
        String result1 = encryption(str1);    
        String result2 = decrypt(str2);
        System.out.println(result1);
        System.out.println(result2);
    }

    private static String decrypt(String str1) {
        char[] charArray = str1.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = decryptDictionary.get(charArray[i]); 
        }
        return new String(charArray);
    }
    private static String encryption(String str1) {
        char[] charArray = str1.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = encryptionDictionary.get(charArray[i]);
        }
        return new String(charArray);
    }
}

全部评论

相关推荐

永不遗忘:才这么点算什么拉黑,我初筛连着挂几十次了,最后还是能进面
点赞 评论 收藏
分享
吴offer选手:学到了,下次面试也放张纸在电脑上,不然老是忘记要说哪几个点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务