How to write palindrome in JavaScript

前端 未结 30 1815
情书的邮戳
情书的邮戳 2020-11-29 02:42

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad

30条回答
  •  感动是毒
    2020-11-29 03:28

    Let us start from the recursive definition of a palindrome:

    1. The empty string '' is a palindrome
    2. The string consisting of the character c, thus 'c', is a palindrome
    3. If the string s is a palindrome, then the string 'c' + s + 'c' for some character c is a palindrome

    This definition can be coded straight into JavaScript:

    function isPalindrome(s) {
      var len = s.length;
      // definition clauses 1. and 2.
      if (len < 2) {
        return true;
      }
      // note: len >= 2
      // definition clause 3.
      if (s[0] != s[len - 1]) {
        return false;
      }
      // note: string is of form s = 'a' + t + 'a'
      // note: s.length >= 2 implies t.length >= 0
      var t = s.substr(1, len - 2);
      return isPalindrome(t);
    }
    

    Here is some additional test code for MongoDB's mongo JavaScript shell, in a web browser with debugger replace print() with console.log()

    function test(s) {
      print('isPalindrome(' + s + '): ' + isPalindrome(s));
    }
    
    test('');
    test('a');
    test('ab');
    test('aa');
    test('aab');
    test('aba');
    test('aaa');
    test('abaa');
    test('neilarmstronggnortsmralien');
    test('neilarmstrongxgnortsmralien');
    test('neilarmstrongxsortsmralien');
    

    I got this output:

    $ mongo palindrome.js
    MongoDB shell version: 2.4.8
    connecting to: test
    isPalindrome(): true
    isPalindrome(a): true
    isPalindrome(ab): false
    isPalindrome(aa): true
    isPalindrome(aab): false
    isPalindrome(aba): true
    isPalindrome(aaa): true
    isPalindrome(abaa): false
    isPalindrome(neilarmstronggnortsmralien): true
    isPalindrome(neilarmstrongxgnortsmralien): true
    isPalindrome(neilarmstrongxsortsmralien): false
    

    An iterative solution is:

    function isPalindrome(s) {
      var len = s.length;
      if (len < 2) {
        return true;
      }
      var i = 0;
      var j = len - 1;
      while (i < j) {
        if (s[i] != s[j]) {
          return false;
        }
        i += 1;
        j -= 1;
      }
      return true;
    }
    

提交回复
热议问题