题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const lines: string[] = [];
rl.on("line", function (line: string) {
lines.push(line);
});
rl.on("close", () => {
console.log(encrypt(lines[0]));
console.log(decrypt(lines[1]));
});
// 加密
const encrypt = (str: string): string => {
const strs = str.split("");
strs.forEach((item, index) => {
if (/[0-9]/.test(item)) {
strs[index] = item === "9" ? "0" : `${parseInt(item) + 1}`;
}
if (/[a-z]/.test(item)) {
strs[index] =
item === "z"
? "A"
: String.fromCharCode(item.toUpperCase().charCodeAt(0) + 1);
}
if (/[A-Z]/.test(item)) {
strs[index] =
item === "Z"
? "a"
: String.fromCharCode(item.toLowerCase().charCodeAt(0) + 1);
}
});
return strs.join("");
};
// 解密
const decrypt = (str: string): string => {
const strs = str.split("");
strs.forEach((item, index) => {
if (/[0-9]/.test(item)) {
strs[index] = item === "0" ? "9" : `${parseInt(item) - 1}`;
}
if (/[a-z]/.test(item)) {
strs[index] =
item === "a"
? "Z"
: String.fromCharCode(item.toUpperCase().charCodeAt(0) - 1);
}
if (/[A-Z]/.test(item)) {
strs[index] =
item === "A"
? "z"
: String.fromCharCode(item.toLowerCase().charCodeAt(0) - 1);
}
});
return strs.join("");
};
