Ads Top

Interview Practice: Javascript Valid Palindrome Solution - isPalindrome()

Palindrome: a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.

In order to write a method for testing if a word or phrase is a pailndrome you can follow these steps

1: Take the initial argument, which is the palindrome that is passed in and strip any special characters an convert to lower case
2: The variable that is created in step one, you want to split it to create an array that can be reversed and then joined back into a string. Once you add the final function - toLowerCase(), you will have the original string that you can match up to the reverse string. At this point, you can simply compare the original string to the revesed string and if they match, then you have a palindrome and can return true

Here is the code to implement this solution
var isPalindrome = function(s) {
const stripped =
s.replace(/[^a-z0-9]/gi, '') // matches any non-alphanumeric character
.toLowerCase()
const reverse =
stripped.split('')
.reverse()
.join('')
.toLowerCase()
if (stripped === reverse) {
return true
}
return false
}
const input = "A man, a plan, a canal: Panama"
console.log(isPalindrome(input)) // output true
const input2 = 'racecar2'
console.log(isPalindrome(input2)) // output false
const input3 = 'ab_a'
console.log(isPalindrome(input3)) // output true
view raw isPalindrome.js hosted with ❤ by GitHub

Taken from Leetcode 125: https://leetcode.com/problems/valid-palindrome/

Leave a Comment

No comments:

Powered by Blogger.