Written in java, it's an optimal solution.
public class PalindromeTest {
public static void main(String[] args) {
for (String input : args) {
if (isValid(input)) {
int mid = input.length()/2;
String firstHalf = input.substring(0, mid);
String secondHalf = input.substring(getProperSecondHalfMid(input.length()), input.length());
System.out.println(input + " is a palindrome: " + areStringsEqual(firstHalf, getReverseString(secondHalf)));
} else {
System.out.println("Sorry, input: " + input + ", is not valid!");
}
}
}
private static int getProperSecondHalfMid(int length) {
return length%2 == 0 ? length/2: length/2 + 1;
}
private static String getReverseString(String secondHalf) {
return (new StringBuffer(secondHalf).reverse().toString());
}
private static String areStringsEqual(String firstHalf, String secondHalf) {
return Boolean.toString(firstHalf.equalsIgnoreCase(secondHalf));
}
private static boolean isValid(String input) {
return !input.isEmpty();
}
}
public static void main(String[] args) {
for (String input : args) {
if (isValid(input)) {
int mid = input.length()/2;
String firstHalf = input.substring(0, mid);
String secondHalf = input.substring(getProperSecondHalfMid(input.length()), input.length());
System.out.println(input + " is a palindrome: " + areStringsEqual(firstHalf, getReverseString(secondHalf)));
} else {
System.out.println("Sorry, input: " + input + ", is not valid!");
}
}
}
private static int getProperSecondHalfMid(int length) {
return length%2 == 0 ? length/2: length/2 + 1;
}
private static String getReverseString(String secondHalf) {
return (new StringBuffer(secondHalf).reverse().toString());
}
private static String areStringsEqual(String firstHalf, String secondHalf) {
return Boolean.toString(firstHalf.equalsIgnoreCase(secondHalf));
}
private static boolean isValid(String input) {
return !input.isEmpty();
}
}
No comments:
Post a Comment