题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
看了其他语言的解题思路 很多都是直接用的映射的方法,相对来说比较简单,这里还是介绍一种传统的解密加密的方法 完整代码如下:
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
let lines = [];
void async function () {
// Write your code here
while(line = await readline()){
lines.push(line);
if (lines.length == 2) {
console.log(encryption(lines[0]));
console.log(decryption(lines[1]));
}
}
}()
function encryption(str){
let arr = str.split('');
for (let i = 0; i < arr.length; i++) {
if (arr[i].match(/[A-Z]/)) {
arr[i] = arr[i] == 'Z' ? 'a' : String.fromCharCode(arr[i].toLowerCase().charCodeAt(0) + 1);
}
else if (arr[i].match(/[a-z]/)) {
arr[i] = arr[i] == 'z' ? 'A' : String.fromCharCode(arr[i].toUpperCase().charCodeAt(0) + 1);
}
else if (arr[i].match(/[0-9]/)){
arr[i] = arr[i] == '9' ? '0' : (parseInt(arr[i])+1).toString();
}
}
let res = arr.join('');
return res;
}
function decryption(str){
let arr = str.split('');
for (let i = 0; i < arr.length; i++) {
if (arr[i].match(/[A-Z]/)) {
arr[i] = arr[i] == 'A' ? 'z' : String.fromCharCode(arr[i].toLowerCase().charCodeAt(0) - 1);
}
else if (arr[i].match(/[a-z]/)) {
arr[i] = arr[i] == 'a' ? 'Z' : String.fromCharCode(arr[i].toUpperCase().charCodeAt(0) - 1);
}
else if (arr[i].match(/[0-9]/)){
arr[i] = arr[i] == '0' ? '9' : (parseInt(arr[i])-1).toString();
}
}
let res = arr.join('');
return res;
}
