How to check if a string is a palindrome
Short answer
A palindrome reads the same left to right and right to left. Compare the string with its reversed copy:
void main() {
String word = "level";
boolean palindrome = word.equals(new StringBuilder(word).reverse().toString());
IO.println(palindrome);
}Output:
trueTwo pointers
Without an extra string: compare characters from both ends and move towards the middle:
boolean isPalindrome(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
if (text.charAt(left) != text.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
void main() {
IO.println(isPalindrome("racecar"));
IO.println(isPalindrome("java"));
}Output:
true
falseA phrase
For phrases, remove everything except letters and digits and bring the text to one case:
void main() {
String phrase = "A man, a plan, a canal: Panama";
String clean = phrase.replaceAll("[^\\p{L}\\p{N}]", "").toLowerCase();
IO.println(clean);
IO.println(clean.equals(new StringBuilder(clean).reverse().toString()));
}Output:
amanaplanacanalpanama
trueCommon mistake
Comparing the strings with ==. The reversed string is a new object, so the result is always false:
void main() {
String word = "level";
String reversed = new StringBuilder(word).reverse().toString();
IO.println(word == reversed);
IO.println(word.equals(reversed));
}Output:
false
trueFunctions used in this recipe
- StringBuilder.reverse() — Reverses the contents of a StringBuilder.
- String.charAt() — Returns the character at the given index.
- String.replaceAll() — Replaces every match of a regular expression.