题解 | #字符串加解密#
字符串加解密
https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a
分别定义加密、解密function 具体代码如下:
//定义加密代码 function encryption (string) { //将输入的string转换为array let arr = string.split('') //定义大写英文字母A-Y的正则表达式 let regexAlphabet1 = /[A-Y]/ //定义小写英文字母a-y的正则表达式 let regexAlphabet2 = /[a-y]/ //定义数字0-8的正则表达式 let regexNum = /[0-8]/ //遍历数组 for (let i = 0; i < arr.length; i++) { //如元素为大写英文字母A-Y if (regexAlphabet1.test(arr[i])) { arr.splice(i, 1, String.fromCharCode(arr[i].toLowerCase().charCodeAt(0)+1)) } //如元素为小写英文字母a-y else if (regexAlphabet2.test(arr[i])) { arr.splice(i, 1, String.fromCharCode(arr[i].toUpperCase().charCodeAt(0)+1)) } //单独讨论小写英文字母z else if (arr[i] == 'z') { arr.splice(i, 1, 'A') } //单独讨论大写英文字母Z else if (arr[i] == 'Z') { arr.splice(i, 1, 'a') } //如元素为数字0-8 else if (regexNum.test(arr[i])) { arr.splice(i, 1, parseInt(arr[i]) + 1) } //单独讨论数字9 else if (arr[i] == 9) { arr.splice(i, 1, 0) } } //返回数组 return arr.join(''); } //解密过程则相反 如下 function decryption (string) { let arr = string.split('') let regexAlphabet1 = /[B-Z]/ let regexAlphabet2 = /[b-z]/ let regexNum = /[1-9]/ for (let i = 0; i < arr.length; i++) { if (regexAlphabet1.test(arr[i])) { arr.splice(i, 1, String.fromCharCode(arr[i].toLowerCase().charCodeAt(0)-1)) } else if (regexAlphabet2.test(arr[i])) { arr.splice(i, 1, String.fromCharCode(arr[i].toUpperCase().charCodeAt(0)-1)) } else if (arr[i] == 'a') { arr.splice(i, 1, 'Z') } else if (arr[i] == 'A') { arr.splice(i, 1, 'z') } else if (regexNum.test(arr[i])) { arr.splice(i, 1, parseInt(arr[i]) - 1) } else if (arr[i] == 0) { arr.splice(i, 1, 9) } } return arr.join(''); } var unencrypted = readline(); console.log(encryption(unencrypted)); var encrypted = readline(); console.log(decryption(encrypted));