
Problem Statement
This problem is from Leetcode – Valid Palindrome. The problem statement is as below:
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome, or false
otherwise.
Solution
This problem is asking us to check whether the given string is a palindrome or not – after removing all non-alphanumeric characters.
- First remove all non-alphanumeric characters from the string.
- Next remove all spaces from the string.
- Now in a for loop compare the respective characters from both ends of the string. If any comparison fails then exit with false.
Lets see the code sample below:
public boolean isPalindrome(String s) {
boolean isPalin = true;
// remove all non-alphanumeric characters
s = s.replaceAll("[^A-Za-z0-9]", "");
// remove spaces
s = s.replace(" ", "");
// convert string to lower case
s = s.toLowerCase();
// if the length of string here is zero then return true
if(s.length() == 0) {
return isPalin;
}
// get the mid-point of the string length
int index = s.length() / 2;
// compare the respective characters from both ends of the string till mid-point
for(int i=0; i<=index; i++) {
if( s.charAt(i) != s.charAt(s.length()-1-i)) {
isPalin = false;
break;
}
}
return isPalin;
}
You can checkout the code from Github here: Valid Palindrome
Whatæ¯ Happening i am new to this, I stumbled upon this I’ve found It positively useful and it has helped me out loads. I hope to contribute & assist other users like its helped me. Good job.
Fantastic blog! Do you have any recommendations for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m totally confused .. Any recommendations? Thank you!