挑战:回文词

时间:2019-03-10 00:01:29

标签: javascript

回文词是向后或向前读相同的单词。 编写一个函数来检查给定的单词是否是回文。字符大小写应忽略。 函数isPalindrome(word) 例如,isPalindrome(“ Deleveled”)应该返回true,因为忽略字符大小写,从而导致“ deleveled”,这是回文,因为它前后读取相同的内容。

function isPalindrome(word)
{
  // Please write your code here.
}
var word = readline()
print(isPalindrome(word))

2 个答案:

答案 0 :(得分:3)

手动:

function isPalindrome(word) {
  word = word.toLowerCase();
  for (var i = 0, j = word.length-1; i < j; i++, j--) {
    if (word[i] !== word[j]) {
      return false;
    }
    return true;
  }
}

console.log(isPalindrome("madam"));
console.log(isPalindrome("foobar"));

图书馆:

function isPalindrome(word) {
  word = word.toLowerCase();
  var half = word.length/2;
  return word.slice(0, half) === word.slice(-half).split("").reverse().join("");
}

console.log(isPalindrome("madam"));
console.log(isPalindrome("foobar"));

无论使用哪种方法,您都可以先通过删除应忽略的字符来规范化字符串。

答案 1 :(得分:1)

资料来源: https://medium.freecodecamp.org/two-ways-to-check-for-palindromes-in-javascript-64fea8191fd7

一种方法,链接上的其他方法:

function palindrome(str) {
  // Step 1. Lowercase the string and use the RegExp to remove unwanted characters from it
  var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;

  var lowRegStr = str.toLowerCase().replace(re, '');
  // str.toLowerCase() = "A man, a plan, a canal. Panama".toLowerCase() = "a man, a plan, a canal. panama"
  // str.replace(/[\W_]/g, '') = "a man, a plan, a canal. panama".replace(/[\W_]/g, '') = "amanaplanacanalpanama"
  // var lowRegStr = "amanaplanacanalpanama";

  // Step 2. Use the same chaining methods with built-in functions from the previous article 'Three Ways to Reverse a String in JavaScript'
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  // lowRegStr.split('') = "amanaplanacanalpanama".split('') = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
  // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].reverse() = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
  // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].join('') = "amanaplanacanalpanama"
  // So, "amanaplanacanalpanama".split('').reverse().join('') = "amanaplanacanalpanama";
  // And, var reverseStr = "amanaplanacanalpanama";

  // Step 3. Check if reverseStr is strictly equals to lowRegStr and return a Boolean
  return reverseStr === lowRegStr; // "amanaplanacanalpanama" === "amanaplanacanalpanama"? => true
}

palindrome("A man, a plan, a canal. Panama");