How to write palindrome in JavaScript

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

    Taking a stab at this. Kind of hard to measure performance, though.

    function palin(word) {
        var i = 0,
            len = word.length - 1,
            max = word.length / 2 | 0;
    
        while (i < max) {
            if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
                return false;
            }
            i += 1;
        }
        return true;
    }
    

    My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.

提交回复
热议问题