It would not be too difficult to determine algorithmically if a word or sentence is a palindrome. There are many ways to solve it but we also need to consider if our solution is not computationally expensive.
I have thought of a simple and yet an efficient solution to our discussion. This is a static method that strips off the punctuations and also white character spacings. The method returns a boolean value true if the input string is a palindrome otherwise it returns false.
public static boolean isPalindrome(String text){
//Sets an index at the far left of the word or phrase
int leftIndex = 0;
//Converts input text into lower case and remove
//any single non-alphanumeric and underscore
text = text.toLowerCase().replaceAll("[\\W\\_*]", "");
//Sets an index at the far right of the word or phrase
int rightIndex = text.length()-1;
while (leftIndex < rightIndex) {
if (!(text.charAt(leftIndex) == text.charAt(rightIndex))) {
//returns a false and get out from the while loop
return false;
}
//gets the indexes from both sides closer
leftIndex++;
rightIndex--;
}
//returns a true if all the characters mirrors to each other
return true;
}
0 comments:
Post a Comment