11. Checking whether a string is a palindrome

Just as a quick reminder, a palindrome (whether a string or a number) looks unchanged when it's reversed. This means that processing (reading) a palindrome can be done from both directions and the same result will be obtained (for example, the word madam is a palindrome, while the word madame is not).

An easy to implement solution consists of comparing the letters of the given string in a meet-in-the-middle approach. Basically, this solution compares the first character with the last one, the second character with the last by one, and so on until the middle of the string is reached. The implementation relies on the while statement:

public static boolean isPalindrome(String str) {

int left = 0;
int right = str.length() - 1;

while (right > left) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}

left++;
right--;
}
return true;
}

Rewriting the preceding solution in a more concise approach will consist of relying on a for statement instead of a while statement, as follows:

public static boolean isPalindrome(String str) {

int n = str.length();

for (int i = 0; i < n / 2; i++) {
if (str.charAt(i) != str.charAt(n - i - 1)) {
return false;
}
}
return true;
}

But can this solution be reduced to a single line of code? The answer is yes.

The Java API provides the StringBuilder class, which uses the reverse() method. As its name suggests, the reverse() method returns the reverse given string. In the case of a palindrome, the given string should be equal to the reverse version of it:

public static boolean isPalindrome(String str) {

return str.equals(new StringBuilder(str).reverse().toString());
}

In Java 8 functional style, there is a single line of code for this as well. Simply define IntStream ranging from 0 to half of the given string and use the noneMatch() short-circuiting terminal operation with a predicate that compares the letters by following the meet-in-the-middle approach:

public static boolean isPalindrome(String str) {

return IntStream.range(0, str.length() / 2)
.noneMatch(p -> str.charAt(p) !=
str.charAt(str.length() - p - 1));
}

Now, let's talk about removing duplicate characters from the given string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.232.187