Thursday, 16 June 2016

How do you test if a word is a palindrome?

A palindrome is a word, or phrase, that when the letters are reversed, the spelling is the same. Some
examples include, “eve,” “level,”.

public static boolean isPalindrome(final String s) {
final String toCheck = s.toLowerCase();
int left = 0;
int right = toCheck.length() - 1;
while (left <= right) {
while(left < toCheck.length() &&
!Character.isLetter(toCheck.charAt(left))) {
left++;
}
while(right > 0 && !Character.isLetter(toCheck.charAt(right))) {
right--;
}
if (left > toCheck.length() || right < 0) {
return false;
}
if (toCheck.charAt(left) != toCheck.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

Or you may check it also by reversing the string and check the equality,

public static boolean isPalindrome(final String s) {
return s.equals(reverse(s));
}

public static String reverse(final String s) {
final StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < builder.length() / 2; i++) {
final char tmp = builder.charAt(i);
final int otherEnd = builder.length() - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd));
builder.setCharAt(otherEnd, tmp);
}
return builder.toString();
}

No comments:

Post a Comment

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...