Function to check palindrome

Asked

Viewed 4,944 times

6

I have the challenge of writing a code to check if a text is a palindrome or not. I haven’t finished the code, at the moment, it’s like this:

function checkPalindrome(str) {     
var direita = [];
for(var i = 0; i<str.length; i++){      
    direita.unshift(str.charAt(i)); 
    }
    console.log(direita);
var esquerda = [];
for (var j=str.length-1; j>=0; j--){
    esquerda.push(str.charAt(j));
}
    console.log(esquerda);
    };

So far I wanted to see if I could read one string normally and the other way around. It would play the two readings in 1 vector each for later, compare them and tell whether it’s palindromic or not.Anyway, it turns out that when we test it on the Google Chrome console or another, it runs only esquerda.push(str.charAt(j)); for the two vectors, not reading the expression in the two necessary directions. What may be wrong?

A palindrome is a text that can be read normally, or reversed, which will have the same meaning. Example: "revive", "blue light", "radar".

5 answers

9

You can reverse the string and compare like this: str === str.split('').reverse().join('')

const testes = ["reviver", "luz azul", "radar", "manhã"];
const checkPalindrome = str => str === str.split('').reverse().join('');
const resultados = testes.map(checkPalindrome);
console.log(resultados);
// dá: true, false, true, false

To ignore white spaces you can do:

const testes = ["reviver", "luz azul", "radar", "manhã"];
const ignoreSpaces = str => str.split(' ').join('');
const checkPalindrome = str => ignoreSpaces(str) === ignoreSpaces(str.split('').reverse().join(''));
const resultados = testes.map(checkPalindrome);
console.log(resultados);
// dá: true, true, true, false

7


If the function is to check, and has this even in the name, it is highly likely that it should return whether it is true or false. And even if it wasn’t that, only if she said explicitly that she should print.

I do not understand what you are trying to do in this code, but if it is what is described in the question is simpler, just go checking the first with the last, the second with the penultimate, and so on until you reach the middle, so you only need to go halfway. Any pair that pierces the condition already ensures that it is not a palindrome and does not need to continue, it will only be a palindrome if it passes through all without fail.

function checkPalindrome(str) {     
    for(var i = 0; i < str.length / 2; i++) if (str[i] != str[str.length - i - 1]) return false;
    return true;
}
console.log(checkPalindrome("radar"));
console.log(checkPalindrome("reviver"));
console.log(checkPalindrome("palindromo"));

I put in the Github for future reference.

The question does not make clear whether to accept sentences, if necessary would have to eliminate the spaces first. Then you can add a previous step, which is less efficient, or you will have to make a more complex algorithm that ignores space, which is significantly more complex and I don’t even know if it will be that efficient.

  • It solved my problem and I also learned more. In fact, I also didn’t think whether I should consider sentences or not. At Code Signal it wasn’t clear to me either. Thank you! @Maniero

2

so that the palindrome that starts with capital letters tb is counted as true use:

function checkPalindrome(str) {
  return str.toLowerCase()==str.split('').reverse().join('').toLowerCase()
}

1

  1. Divide the word into an array, saving it into a variable.
  2. Invert the array.
  3. Mound again.
  4. Compare the initial string with the reverse.

0.52 ms

function checkPalindrome(str){
  let reversed = str.split("").reverse().join("")
  return str === reversed
}


console.log(checkPalindrome("reviver"));

console.log(checkPalindrome("luz azul"));

console.log(checkPalindrome("manhã"));

You can simplify even more by using ES6:

function checkPalindrome(str){
  let reversed = [...str].reverse().join("")
  return str === reversed
}

 console.log(checkPalindrome("reviver"));

console.log(checkPalindrome("luz azul"));

console.log(checkPalindrome("manhã"));

0.30 ms

function checkPalindrome(str){
  let le = str.length;
  if (le === 0 || le === 1) {
    return true;
  }
  if (str[0] === str[le - 1]) {
    return checkPalindrome(str.slice(1, le - 1) );
  }  
  return false;
};

    console.log(checkPalindrome("reviver"));

    console.log(checkPalindrome("luz azul"));

    console.log(checkPalindrome("manhã"));

0.20 ms

In this solution, we will invert the string, this time using a loop for checking whether the letters are exactly the same on both sides.

  1. Declare a variable with the string length.
  2. Declare a loop for, using half the length of the string as a reference point.
  3. Check that each letter is equal to its equivalent on the other side (measured with index - 1).

function checkPalindrome(str) {
 let l = str.length;
 for (let i = 0; i < l/2; i++) {
  if (str[i] !== str[l - 1 - i]) {
   return false;
  }
 }
 return true;
}

        console.log(checkPalindrome("reviver"));

        console.log(checkPalindrome("luz azul"));

        console.log(checkPalindrome("manhã"));

Source

See more solutions at Stackoverflow

1

improving the code of a given answer. It did not take the case that the word started being equal, it already returned true, but it was not necessarily a palindrome!

const checkPalindrome = (str) => {
    let result = ''
    for (var i = 0; i<str.length / 2; i++ ) {
        if (str[i] !== str[str.length -i -1]) return result = false
        result = true
    }
    return result
}

console.log(checkPalindrome("palindromo"));
console.log(checkPalindrome("radar"));
console.log(checkPalindrome("reviver"));
console.log(checkPalindrome("antgretdna"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.