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