我有以下内容:

function checkPalindrom(palindrom)
{

    for( var i = palindrom.length; i > 0; i-- )
    {
        if( palindrom[i] = palindrom.charAt(palindrom.length)-1 )
        {
            document.write('the word is palindrome.');
        }else{
            document.write('the word is not palindrome!');
        }
    }
}
checkPalindrom('wordthatwillbechecked');

我的代码有什么问题?我想检查一下这个词是否是回文。

最佳答案

也许我会建议替代解决方案:

function checkPalindrom (str) {
  return str == str.split('').reverse().join('');
}

UPD。但是请记住,这几乎是“作弊”方法,是对语言功能的智能用法的演示,但不是最实用的算法(时间O(n),空间O(n))。对于现实生活中的应用程序或编码面试,您绝对应该使用循环解决方案。 Jason Sebring在此线程中发布的one既简单又高效(时间O(n),空间O(1))。

09-20 22:30