In my previous post where I discussed about the two sum problem, I told that the solution for the Valid Palindrome and anagram are somewhat similar. However, the palindrome is much more easier than anagram. In this problem, we have to know if a phrase is a palindrome or not. For those who do not know what is Palindrome, “A phrase is a palindrome if it reads the same forward and backward, after removing all the spaces and non-alphanumeric characters and it shouldn’t be case sensitive. “
From the definition, we can understand couple of things
- We have to transform the given text to either lowercase or uppercase
- We have to remove all the spaces
- We only need to get the words no extra non alpha characters
So we will first transformed all the characters to lowercase by using a lodash function called lowerCase. Once that is done, we will remove all the spaces by writing the below code
const removedSpaces = lowerCase.split(' ').join('');
Once that is done now we have to remove all the extra non-alphanumeric characters. I was looking at the lodash library with does have a very good function called words. I really liked the functionality so I used that one. Now that I have removed all the clutter, all I have to do is to reverse the original string and check if the original and the reversed string are same. I have wrote the whole code in TypeScript and added it below.
Solution
Hello readers, If you are like me who wants to get better at coding, please check out my other blog posts where I solve other leetcode problems.
In the next post, I am going to solve 3Sum problem. You can also check out my other blog post as well.
Pingback: Two Sum - Leetcode Solution using JavaScript - Al Fahim