Question

This is a code I used for the coderbyte challenge "Palindrome". The challenge is to return true if str is the same foward and backward(a palindrome). I got all possible points but I know my code is a little ugly. What would be a more efficient way to write this code. It looks like I am repeating myself and it seems like something that could maybe be written with a for loop.I also see how it could return true when its really false if there was a longer palindrome without the use of a for loop:

function Palindrome(str) { 
    var low=str.toLowerCase()
    var first = low.charAt(0);
    var last = low.charAt(low.length-1);
    var mid = low.charAt(1);
    var mid1 = low.charAt(low.length-2);


       if(first===last)
        if(mid===mid1)


        {
           return true    
        }
            else
        {
            return false    
        }
        else
        {
            return false
        }
        }
print(Palindrome(readline()));           
Était-ce utile?

La solution

To check the string if it's a palindrome you just should compare it to its reversed version.
Say the word hello is not a palndrome because its reversed version olleh is not equal to it. But the word eye is a palindrome same as word abba because they're equal to their reversed versions.

Code example:

(function() {
    var reverseStr,
        isPalindrome,
        testStrings;

    reverseStr = function(str) {
        var chars = [];
        for(var i = str.length - 1; i > -1; i--) {
            chars.push(str[i]);
        }
        return chars.join('');
    };

    isPalindrome = function(str, ignoreCase) {
        if(ignoreCase) {
            str = str.toLowerCase();
        }
        return str === reverseStr(str);
    };

    testStrings = ['abba', 'hello', 'eye'];

    for(var i = 0, l = testStrings.length; i < l; i++) {
        var word = testStrings[i];
        console.log('Word "%s" is %sa palindrome',
            word,
            isPalindrome(word) ? '' : 'not ');
    }
})();

DEMO #1

Another way that could work faster is listed below. Here you don't receive a reversed string to compare but walking towards the middle of the string from its start and its end.

var isPalindrome = function(str, ignoreCase) {
    var length,
        last,
        halfLength,
        i;
    if(ignoreCase) {
        str = str.toLowerCase();
    }
    length = str.length;
    last = length - 1;
    halfLength = Math.ceil(length / 2);
    for(i = 0; i < halfLength; i++) {
        if(str[i] !== str[last - i]) {
            return false;
        }
    }
    return true;
};

DEMO #2

Autres conseils

function Palindrome(str) { 
    str = str.toLowerCase();
    str = str.split(" ").join("");
    return str == str.split("").reverse().join("");
}

This is what I ended up with. Made sure the string was all lowercase so it wouldn't read a potentially true parameter as false, got rid of the spaces, and then returned true/false based off whether or not the string was equal to it's reverse.

Here is an even easier way:

var isPalindrome = function(string) {
    string = string.toLowerCase();
    if(string.length===0){
    return false;
    }
    for (var i = 0; i < Math.ceil(string.length/2); i++) {
        var j = string.length-1-i;
        var character1 = string.charAt(i);
        var character2 = string.charAt(j);
        if (character1 !== character2) {
            return false;
        }
    }
    return true;
};

I came across this palindrome coding challenge with a twist, you have to replace all the non-alphanumeric characters(punctuation, spaces and symbols) and of course change the string into lowercase. This is my solution.

 function palindrome(str) {

  var low = str.toLowerCase(); 
  var filteredStr = low.replace(/[^0-9a-z]/gi, "");  
  var split = filteredStr.split("");
  var backward = split.reverse();
  var join = backward.join("");


  if (filteredStr === join) {
    return true;
  } else {
    return false;
  }

}

if you care about number of lines of code, here's smaller one

 function palindrome(str) {

  var low = str.toLowerCase(); 
  var filteredStr = low.replace(/[^0-9a-z]/gi, "");  
  var backward = filteredStr.split("").reverse().join("");


  if (filteredStr === backward) {
    return true;
  } else {
    return false;
  }

}

the code is beginner friendly and self explanatory, but if you have any questions regarding the code, feel free to ask ;)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top