Write an efficient algorithm to check if a string is a palindrome. A string is a palindrome if the string matches the reverse of string.
Example: 1221 is a palindrome but not 1121.
=======================================================================
package com.test.arun;
/**
* Used to check if a word or a phrase reads the same backward as forward.
*/
public class Palindrome {
private static String[] words = new String[] { "aibohphobia", "deleveled",
"1221", "evitative", "Rotavator", "123451", "releveler", "dish",
"apple" };
public static void main(String... args) {
for (String word : words) {
if (isPalindrome(word)) {
System.out.println(word + " is a palindrome.");
} else {
System.out.println(word + " is not a palindrome.");
}
}
}
/**
* Checks if the word is a palindrome.
*
* @param str
* @return
*/
private static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
int half = right / 2;
// Reads the character from left and right simultaneously, then compare.
for (int i = 0; i < half; i++, left++, right--) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
}
return true;
}
}
Example: 1221 is a palindrome but not 1121.
=======================================================================
package com.test.arun;
/**
* Used to check if a word or a phrase reads the same backward as forward.
*/
public class Palindrome {
private static String[] words = new String[] { "aibohphobia", "deleveled",
"1221", "evitative", "Rotavator", "123451", "releveler", "dish",
"apple" };
public static void main(String... args) {
for (String word : words) {
if (isPalindrome(word)) {
System.out.println(word + " is a palindrome.");
} else {
System.out.println(word + " is not a palindrome.");
}
}
}
/**
* Checks if the word is a palindrome.
*
* @param str
* @return
*/
private static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
int half = right / 2;
// Reads the character from left and right simultaneously, then compare.
for (int i = 0; i < half; i++, left++, right--) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
}
return true;
}
}
0 comments:
Post a Comment