我已经花了很多时间试图解决这个问题,但我得出的结论是,经过几个小时的努力,我需要帮助。我知道非常接近,但无法摆脱单词之间的空格。这是我的代码:
function rot13(encodedStr) {
var codeArr = encodedStr.split("");
var decodedArr = [];
var letters = ["A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var space = " ";
var location = 0;
var temp = [];
for(var i = 0; i<codeArr.length; i++){
if(letters[i] !== " "){
location = letters.indexOf(codeArr[i]);
decodedArr.push(letters[(location+13)%26]);
}else
decodedArr.push(letters[i]);
}
return decodedArr.join("");
}
rot13("SERR CVMMN!");
这应该返回“免费比萨饼!”
答案 0 :(得分:3)
让我们将所有字母标记为大写,以避免rot13('SERR CVMMN!');
和rot13('SeRR cvMmn!');
之间的歧义
var codeArr = encodedStr.toUpperCase().split(""); // sanitize input.
应传递非字母字符。空间不是特例
if (/[A-Z]/.test(codeArr[i])) { // if the encoded character is an alphabet character
// decode the character and push it on the decodedArr
} else {
decodedArr.push(codeArr[i]); // let things like spaces and !
// pass through to the output.
}
我认为你的逻辑有点倒退。而不是循环使用字母表为什么不循环编码文本并按顺序解码呢?
for (var i = 0; i < codeArr.length; i += 1) {
if (/[A-Z]/.test(codeArr[i])) { // if the encoded character is an alphabet character
// decode the character and push it on the decodedArr
// the decoded character is 13 ahead of the current character in base 26.
var ACode = 'A'.charCodeAt(); // 65
var letter = codeArr[i];
var letterCode = letter.charCodeAt() - ACode; // ASCII code
letterCode = (letterCode + 13) % 26;
decodedArr.push(letters[letterCode]);
} else {
decodedArr.push(codeArr[i]); // let things like spaces and !
// pass through to the output.
}
}