字符串加密

字符串加密

http://www.nowcoder.com/questionTerminal/e4af1fe682b54459b2a211df91a91cf3

我们用一个长度为26的int数组,记录key中每个字母第一次出现的位置,为了与没出现的字母做出区分,记录的位置从1开始算。假设key中有i个不重复的字母,那在新的字典中,没出现的字母一定是从i位开始依次排列,前面的0到i-1是key中出现的字母。构造出新字典后,直接对data中的字符一个个转换就可以了。
代码如下

import java.util.*;
public class Main{

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            char[] key = sc.nextLine().toLowerCase().toCharArray();
            char[] data=sc.nextLine().toCharArray();
            int dlen=data.length;
            char[] encrypt=new char[dlen];
            int[] zidian=new int[26];
            int[] realKey=new int[26];
            int klen=key.length;
            int newLen=klen;
            for(int i=0;i<klen;i++){
                if(zidian[(int)key[i]-97]==0){
                    zidian[(int)key[i]-97]=i+1-(klen-newLen);
                }else{
                    newLen--;
                }
            }
            int other=newLen;
            for(int i=0;i<26;i++){
                if(zidian[i]==0){
                    realKey[other++]=i;
                }else{
                    realKey[zidian[i]-1]=i;
                }
            }
            for(int i=0;i<dlen;i++){
                char c=data[i];
                if(c==' ') {
                    encrypt[i]=' ';
                    continue;
                }
                if(c>='A'&&c<='Z'){
                    encrypt[i]=(char)(realKey[(int)c-65]+65);
                }else{
                    encrypt[i]=(char)(realKey[(int)c-97]+97);
                }
            }
            System.out.println(encrypt);
        }

    }
}
全部评论
37行,realKey本来就是大写字符数组,没必要减一下再加一下再转成字符吧
点赞
送花
回复
分享
发布于 2021-03-16 02:00

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务