How to write palindrome in JavaScript

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

    The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.

    Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.

    isPalindrome():

    Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.

    for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.

    Here's the code:

    /**
     * TODO: If func counts out, let it return 0
     *  * Assume !isPalindrome (invert logic)
     */
    function isPalindrome(S){
        var s = S
          , len = s.length
          , mid = len/2;
          , i = 0, j = len-1;
    
        while(i=mid){
                var r = s.charAt(j);
                if(l === r){
                    console.log('@while *', i, l, '...', j, r);
                    --j;
                    break;
                }
                console.log('@while !', i, l, '...', j, r);
                return 0;
            }
            ++i;
        }
        return 1;
    }
    
    var nooe = solution('neveroddoreven');  // even char length
    var kayak = solution('kayak');  // odd char length
    var kayaks = solution('kayaks');
    
    console.log('@isPalindrome', nooe, kayak, kayaks);
    

    Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.

提交回复
热议问题