题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
const rl = require("readline").createInterface({ input: process.stdin, output: process.stdout }); const inputs = []; rl.on('line', (line) => { inputs.push(line); }).on('close', () => { const encodeStr = encode(inputs[0]); console.log(encodeStr); const decodePwd = decode(inputs[1]); console.log(decodePwd); }) function encode(str) { let res = ""; for (let i = 0; i < str.length; i++) { const temp = str[i]; if (/\d/.test(temp)) { let n = temp == "9" ? 0 : parseInt(temp) + 1; res += n; } else if (/[A-Z]/.test(temp)) { let C = temp == "Z" ? "a" : String.fromCharCode(temp.charCodeAt() + 1); res += C.toLowerCase(); } else if (/[a-z]/.test(temp)) { let c = temp == "z" ? "A" : String.fromCharCode(temp.charCodeAt() + 1); res += c.toUpperCase(); } else { res += temp; } } return res; } function decode(pwd) { let res = ''; for(let i = 0; i < pwd.length; i++) { const temp = pwd[i]; if(/\d/.test(temp)) { let n = temp == '0' ? 9 : parseInt(temp) - 1; res += n; } else if(/[A-Z]/.test(temp)) { let c = temp == 'A' ? 'z' : String.fromCharCode((temp.charCodeAt() - 1)); res += c.toLowerCase(); } else if(/[a-z]/.test(temp)) { let c = temp == 'a' ? 'Z' : String.fromCodePoint((temp.charCodeAt() - 1)); res += c.toUpperCase(); } else { res += temp; } } return res; }
步骤:
1、 加密encode:
- 数字:9 -> 0, 0-8 -> i + 1
- A-Z:Z -> A -> a,A - Y -> String.fromCharCode(i.charCodeAt() + 1) -> toLowerCase()
- a-z: z -> a -> A, a - y -> String.fromCharCode(i.charCodeAt + 1) -> toUpperCase();
- 其它字符: 不变
2、解密decode:
上述过程的逆过程