How to write palindrome in JavaScript

前端 未结 30 1798
情书的邮戳
情书的邮戳 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:37

    Look at this:

    function isPalindrome(word){
        if(word==null || word.length==0){
            // up to you if you want true or false here, don't comment saying you 
            // would put true, I put this check here because of 
            // the following i < Math.ceil(word.length/2) && i< word.length
            return false;
        }
        var lastIndex=Math.ceil(word.length/2);
        for (var i = 0; i < lastIndex  && i< word.length; i++) {
            if (word[i] != word[word.length-1-i]) {
                return false;
            }
         }
         return true;
    } 
    

    Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!

    Since the string is an array of char no need to use charAt functions!!!

    Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome

提交回复
热议问题