Some problems in programming have the status of classic ones. Typically, such tasks are related to mathematics and they are very fond of asking students of Computer Science specialties, as well as job seekers at interviews. They are good because they help to set up your thinking in a programmer way quite well, as well as train it. One of such problems is checking whether a string is a palindrome, and we are going to consider it in this article.
At least the result is what we expected from it:
What is a palindrome and why be able to look for them
A palindrome is a number, letter combination, word or text that reads the same in both directions. To summarize, a palindrome can be called any set of characters that is symmetrical about its middle. The word is from Greek roots that literally derive “running back” (palin is “again, back,” and dromos, “running.”). Palindrome in Java means the same as in general meaning. Examples of palindromes:- 1881
- aaqquqqaa
- pop
- Noon
- level
- Rotator
- My Gym
- Madam I am Adam
- Now, sir, a war is won!
Palindrome algorithm code example
Let's think. A string is a sequence of characters, one might say, an array of char. It would be most logical to follow this sequence from both sides to the middle and compare the extreme characters. If until we reach the middle all our characters will match, then we have a palindrome. Let's create a boolean method validPalindrome(String s) to check if String is palindrome. Java code is here:
public class PalindromeTest1 {
//method to check if a string is palindrome
public static boolean validPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "level";
String s2 = "cool";
String s3 = "Madam";
String s4 = "Now, sir, a war is won!"
boolean b1 = validPalindrome(s1);
boolean b2 = validPalindrome(s2);
boolean b3 = validPalindrome(s3);
boolean b4 = validPalindrome(s4);
System.out.println("is " + s1 + " a palindrome? " + b1);
System.out.println("is " + s2 + " a palindrome? " + b2);
System.out.println("is " + s3 + " a palindrome? " + b3);
System.out.println("is " + s4 + " a palindrome? " + b4);
}
}
In the main method, we check for palindromic strings “level”, “cool”, “Madam” and "Now, sir, a war is won!". As you can see, the first, third and fourth are palindromes, but the second is not. What will the program give?
is level a palindrome? true
is cool a palindrome? false
is Madam a palindrome? false
is Now, sir, a war is won! a palindrome? false
So, the first is a palindrome, the second is not. However, what is wrong with the third and fourth? Why is the result false?
You probably already guessed that the point is that some characters in this string are uppercase and some are lowercase, and for Java M and m are two different characters. Let's improve the program to take this difference into account. Here is a program to check if a string is a palindrome that solves upper and lowercase problems.
public class PalindromeTest2 {
//lowercase and uppercase characters should be treated the same:
public static boolean validPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
return false;
}
return true;
}
public static void main(String[] args) {
String s1 = "level";
String s2 = "cool";
String s3 = "Madam";
String s4 = "Now, sir, a war is won!"
boolean b1 = validPalindrome(s1);
boolean b2 = validPalindrome(s2);
boolean b3 = validPalindrome(s3);
boolean b4 = validPalindrome(s4);
System.out.println("is " + s1 + " a palindrome? " + b1);
System.out.println("is " + s2 + " a palindrome? " + b2);
System.out.println("is " + s3 + " a palindrome? " + b3);
System.out.println("is " + s4 + " a palindrome? " + b4);
}
}
This time the result is more predictable for us:
is level a palindrome? true
is cool a palindrome? false
is Madam a palindrome? true
is Now, sir, a war is won! a palindrome? false
Well…not exactly predictable. The situation with “Madam” is getting better, but what with our long and happy palindrome “Now, sir, a war is won!”. It’s quite easy, if you remember that all spaces and punctuation symbols are the same as letters for Java. So we need to improve our algorithm again to correct this oversight. Let's teach our program to ignore spaces and punctuation. Simply put, we ignore all non-alphanumeric characters. Here is the improved palindrome program in Java.
public class PalindromeTest3 {
//in addition to the above, ignore all non alphanumeric chars like punctuation and spaces
private static boolean isAlphanumeric(char c) {
return Character.isAlphabetic(c) || Character.isDigit(c);
}
public static boolean validPalindromeIgnorePunctuation(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
// skip chars we should ignore
while (j >= 0 && !isAlphanumeric(s.charAt(j))) j--;
while (i < s.length() && !isAlphanumeric(s.charAt(i))) i++;
// overskipped -> nothing left to validate
if (i >= j) return true;
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
return false;
}
return true;
}
public static void main(String[] args) {
String s1 = "level";
String s2 = "cool";
String s3 = "Madam";
String s4 = "Now, sir, a war is won!";
boolean b1 = validPalindromeIgnorePunctuation(s1);
boolean b2 = validPalindromeIgnorePunctuation(s2);
boolean b3 = validPalindromeIgnorePunctuation(s3);
boolean b4 = validPalindromeIgnorePunctuation(s4);
System.out.println("is " + s1 + " a palindrome? " + b1);
System.out.println("is " + s2 + " a palindrome? " + b2);
System.out.println("is " + s3 + " a palindrome? " + b3);
System.out.println("is " + s4 + " a palindrome? " + b4);
}
}
is level a palindrome? true
is cool a palindrome? false
is Madam a palindrome? true
is Now, sir, a war is won! a palindrome? true
Perhaps, if you are just starting to program, it is difficult for you to understand how the string traversal and comparison algorithms work. Of course, it is better to deal with this, but you can write a simplified version of the very passage through the array of characters, which in fact is a string. You can use the StringBuffer.reverse method to check if a string is a palindrome. Let's do the simplest version without checking for non-alphanumeric symbols and upper and lowercase.
public class PalindromeTest5 {
public static boolean validPalindrome(String s) {
StringBuffer buffer = new StringBuffer(s);
buffer.reverse();
String data = buffer.toString();
if (s.equals(data)) {
return true;
}
return false;
}
public static void main(String[] args) {
String s1 = "level";
String s2 = "cool";
String s3 = "Madam";
String s4 = "Now, sir, a war is won!";
boolean b1 = validPalindrome(s1);
boolean b2 = validPalindrome(s2);
boolean b3 = validPalindrome(s3);
boolean b4 = validPalindrome(s4);
System.out.println("is " + s1 + " a palindrome? " + b1);
System.out.println("is " + s2 + " a palindrome? " + b2);
System.out.println("is " + s3 + " a palindrome? " + b3);
System.out.println("is " + s4 + " a palindrome? " + b4);
}
}
The result is the same as in the very first example
is level a palindrome? true
is cool a palindrome? false
is Madam a palindrome? false
is Now, sir, a war is won! a palindrome? false
If you want, you may improve this program such as we did with the first example.
To reinforce what you learned, we suggest you watch a video lesson from our Java Course
GO TO FULL VERSION