Script – 19-47 Feb 2

I am trying to create a palindrome algorithm to make a word a palindrome and return the index I have to remove to make it a palindrome. I came up with this:
function palindromeIndex(s) {
let re = /[\W_]/g;

let lowRegStr = s.toLowerCase().replace(re, "").split("");
let reverseStr = s.toLowerCase().replace(re, "").split("").reverse();
let removed;
let removedRev;

if (lowRegStr.join("") === reverseStr.join("")) {
return -1;
}

for (let i = 0, k = s.length - 1; i < s.length; i++, k--) {
removed = lowRegStr.splice(i, 1);
removedRev = reverseStr.splice(k, 1);

if (lowRegStr.join("") === reverseStr.join("")) {
return i;
}
lowRegStr.splice(i, 0, ...removed);
reverseStr.splice(k, 0, ...removedRev);
}

return -1;
}
console.log(palindromeIndex("eye"));
function palindromeIndex(s) {
let re = /[\W_]/g;

let lowRegStr = s.toLowerCase().replace(re, "").split("");
let reverseStr = s.toLowerCase().replace(re, "").split("").reverse();
let removed;
let removedRev;

if (lowRegStr.join("") === reverseStr.join("")) {
return -1;
}

for (let i = 0, k = s.length - 1; i < s.length; i++, k--) {
removed = lowRegStr.splice(i, 1);
removedRev = reverseStr.splice(k, 1);

if (lowRegStr.join("") === reverseStr.join("")) {
return i;
}
lowRegStr.splice(i, 0, ...removed);
reverseStr.splice(k, 0, ...removedRev);
}

return -1;
}
console.log(palindromeIndex("eye"));
It works fine but after running tests I discovered its not efficient. What other efficient way can be used?
S
Script806d ago
palindromeIndex("eye") Input is a string Expected output should be -1 because it's a palindrome already But if we have "eyes", expected output should be 3 which is the index of the letter needed to be removed to make it a palindrome Definition of palindrome : a word, verse, or sentence (such as "Able was I ere I saw Elba") or a number (such as 1881) that reads the same backward or forward.
UU
Unknown User805d ago