Palindrome.
Here’s an intro to Palindrome. Since this technique is quite useful when solving not only coding challenges but also real-world problems, it’s great timing to learn about it.
Palindrome is a word I’d never heard of until I found this coding challenge. And here’s the definition of palindrome.
a word, phrase, or sequence that reads the same backwards as forwards, e.g. madam or nurses run.
Google search result
And here’s the challenge:
Given a string, determine if it is a palindrome, considering only alphanumerical characters and ignoring case sensitivity.
AMd here is some examples of palindrome (image 01).
In the case of a sentence that includes commas and spaces, you may need to eliminate them.
Move inwards:
To determine the word (sentence) is actually a palindrome, there are a few methods we can take advantage of. Here’s one way where we have two pointers that loop through inwards until numbing against each other (image 03).
And here’s something you need to be aware of. If the length of the word is odd, the pointers would bump against each other in the middle (image 04).
And if it’s even, the pointers would end up like this (image 05).
Coding solution:
class palindromesFromOutside {
public static boolean palindromeFinder(String palindrome){
palindrome = palindrome.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
int left = 0;
int right = palindrome.length() - 1;
while (left <= right) {
if (palindrome.charAt(left) != palindrome.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String a = "aabaa";
System.out.println(palindromeFinder(a));
}
}
Move outwards:
And here’s another example in which pointers move outwards (image 06).
And this is if the length were even (image 08).
Coding solution:
class palindromesFromInside {
public static boolean isPalindrome(String input) {
String clean = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
int left = 0;
int right = clean.length() - 1;
while (left < right) {
if (clean.charAt(left) != clean.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String test = "race a car";
System.out.println(isPalindrome(test));
}
}
Compare against the reversed version:
Coding solution:
class palindromesCompareReverse {
public boolean palindromeFinder(String palindrome){
String s = palindrome.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
String reversed = "";
// starts from left to right
for(int i = 0; i < s.length() - 1; i++) {
// starts from the opposite direction(right to left)
char ch = s.charAt(i);
reversed = ch + reversed;
}
if (s.equals(reversed)) {
return true;
}
return false;
}
public static void main(String[] args) {
String a = "raceacar";
palindromesCompareReverse p = new palindromesCompareReverse();
System.out.println(p.palindromeFinder(a));
}
}