Palindrome check in Javascript

2019-01-02 18:27发布

i have the following:

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');

What is wrong with my code? i want to check if the word is palindrome.

标签: javascript
30条回答
泪湿衣
2楼-- · 2019-01-02 18:31

As a much clearer recursive function: http://jsfiddle.net/dmz2x117/

function isPalindrome(letters) {

    var characters  = letters.split(''),
        firstLetter = characters.shift(),
        lastLetter  = characters.pop();

    if (firstLetter !== lastLetter) {
        return false;
    }

    if (characters.length < 2) {
        return true;
    }

    return isPalindrome(characters.join(''));

}
查看更多
人间绝色
3楼-- · 2019-01-02 18:31

I thought I'd share my own solution:

function palindrome(string){
    var reverseString = '';
    for(var k in string){
       reverseString += string[(string.length - k) - 1];
    }
  if(string === reverseString){
    console.log('Hey there palindrome');
  }else{
    console.log('You are not a palindrome');
  }
}
palindrome('ana');

Hope will help someone.

查看更多
宁负流年不负卿
4楼-- · 2019-01-02 18:35

I found this on an interview site:

Write an efficient function that checks whether any permutation of an input string is a palindrome. You can ignore punctuation, we only care about the characters.

Playing around with it I came up with this ugly piece of code :)

function checkIfPalindrome(text) {
    var found = {};
    var foundOne = 0;
    text = text.replace(/[^a-z0-9]/gi, '').toLowerCase();
    for (var i = 0; i < text.length; i++) {
        if (found[text[i]]) {
            found[text[i]]++;
        } else {
            found[text[i]] = 1;
        }
    }
    for (var x in found) {
        if (found[x] === 1) {
            foundOne++;
            if (foundOne > 1) {
                return false;
            }
        }
    }
    for (var x in found) {
        if (found[x] > 2 && found[x] % 2 && foundOne) {
            return false;
        }
    }
    return true;
}

Just leaving it here for posterity.

查看更多
临风纵饮
5楼-- · 2019-01-02 18:36

Sharing my fast variant which also support spaces

function isPalindrom(str) {
  var ia = 0;
  var ib = str.length - 1;
  do {
    if (str[ia] === str[ib]) continue;

    // if spaces skip & retry
    if (str[ia] === ' ' && ib++) continue;
    if (str[ib] === ' ' && ia--) continue;

    return false;
  } while (++ia < --ib);
  return true;
}
var palindrom="never odd or even";
var res = isPalindrom(palindrom);
document.getElementById('check').innerHTML ='"'+ palindrom + '"'+" checked to be :" +res;
<span id="check" />

查看更多
大哥的爱人
6楼-- · 2019-01-02 18:38

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 l = s.charAt(i);
        while(j>=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.

查看更多
爱死公子算了
7楼-- · 2019-01-02 18:42

First problem

= is assign == is compare

Second problem, Your logic here is wrong

palindrom.charAt(palindrom.length)-1

You are subtracting one from the charAt and not the length.

Third problem, it still will be wrong since you are not reducing the length by i.

查看更多
登录 后发表回答