How to write palindrome in JavaScript

前端 未结 30 1672
情书的邮戳
情书的邮戳 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;
    }
    
    0 讨论(0)
  • 2020-11-29 03:28

    How about this one?

    function pall (word) {
    
        var lowerCWord = word.toLowerCase();
        var rev = lowerCWord.split('').reverse().join('');
    
        return rev.startsWith(lowerCWord);
        }
    
    pall('Madam');
    
    0 讨论(0)
  • 2020-11-29 03:30

    This function will remove all non-alphanumeric characters (punctuation, spaces, and symbols) and turn everything lower case in order to check for palindromes.

    function palindrome(str){
    
        var re = /[^A-Za-z0-9]/g;
        str = str.toLowerCase().replace(re, '');
        return str == str.split('').reverse().join('') ? true : false;
    
    }
    
    0 讨论(0)
  • 2020-11-29 03:31

    ES6 way of doing it. Notice that I take advantage of the array method reduceRight to reverse a string (you can use array methods on strings if you give the string as context, as low level - strings are arrays of chars). No it is not as performant as other solutions, but didn't see any answer that came it it using es6 or higher order functions so figured I'd throw this one out there.

    const palindrome = str => {
      const middle = str.length/2;
      const left = str.slice(0, middle)
      const right = Array.prototype.reduceRight.call(str.slice(Math.round(middle)), (str, char) => str + char, '')
      return left === right;
    }
    
    0 讨论(0)
  • 2020-11-29 03:32

    I think following function with time complexity of o(log n) will be better.

        function palindrom(s){
        s = s.toString();
        var f = true; l = s.length/2, len = s.length -1;
        for(var i=0; i < l; i++){
                if(s[i] != s[len - i]){
                        f = false; 
                        break;
                }
        }
        return f;
    
        }
    

    console.log(palindrom(12321));

    0 讨论(0)
  • 2020-11-29 03:33
    function palindrome(str) {
        var lenMinusOne = str.length - 1;
        var halfLen = Math.floor(str.length / 2);
    
        for (var i = 0; i < halfLen; ++i) {
            if (str[i] != str[lenMinusOne - i]) {
                return false;
            }
        }
        return true;
    }
    

    Optimized for half string parsing and for constant value variables.

    0 讨论(0)
提交回复
热议问题