华为-字符串加解密
(java实现)
题目描述:
1、对输入的字符串进行加解密,并输出。
2、加密方法为:
当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a;
当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0;
其他字符不做变化。
3、解密方法为加密的逆过程。
本题含有多组样例输入。
输入描述:
输入说明 输入一串要加密的密码 输入一串加过密的密码
输出描述:
输出说明 输出加密后的字符 输出解密后的字符
示例1:
输入
abcdefg BCDEFGH
输出
BCDEFGH abcdefg
问题分析:
略
相关知识:
略
算法实现:
略
参考代码:
法一:
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { //读入数据 String s1 = input.nextLine(); String s2 = input.nextLine(); //加密 String sm1 = "1234567890"; String sm2 = "bcdefghijklmnopqrstuvwxyza"; char[] smc1 = sm1.toCharArray(); char[] smc2 = sm2.toCharArray(); char[] res1 = new char[s1.length()]; char[] s1ch = s1.toCharArray(); int tmp = 0; for (int i=0; i<s1.length(); i++) { if (s1ch[i]>='0' && s1ch[i]<='9') //数字0-9 { res1[i] = smc1[s1ch[i]-'0']; }else if (s1ch[i]>='A' && s1ch[i]<='Z') //字母A-Z,转小写 { res1[i] = smc2[s1ch[i]+32-'a']; }else if (s1ch[i]>='a' && s1ch[i]<='z') //字母a-z,转大写 { res1[i] = (char)(smc2[s1ch[i]-'a']-32); } } System.out.println(res1); //解密 String ms1 = "9012345678"; String ms2 = "zabcdefghijklmnopqrstuvwxy"; char[] msc1 = ms1.toCharArray(); char[] msc2 = ms2.toCharArray(); char[] res2 = new char[s2.length()]; char[] s2ch = s2.toCharArray(); for (int i=0; i<s2.length(); i++) { if (s2ch[i]>='0' && s2ch[i]<='9') //数字0-9 { res2[i] = msc1[s2ch[i]-'0']; }else if (s2ch[i]>='A' && s2ch[i]<='Z') //字母A-Z,转小写 { res2[i] = msc2[s2ch[i]+32-'a']; }else if (s2ch[i]>='a' && s2ch[i]<='z') //字母a-z,转大写 { res2[i] = (char)(msc2[s2ch[i]-'a']-32); } } System.out.println(res2); } } }
法二:
const string helper1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const string helper2 = "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza1234567890"; void Encrypt(string str){ string res; for (int i = 0; i < str.size(); i++) { res += helper2[helper1.find(str[i])]; } cout << res << endl; } void unEncrypt(string str){ string res; for (int i = 0; i < str.size(); i++) { res += helper1[helper2.find(str[i])]; } cout << res << endl; }