Check if given string is palindrome
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar.
class PalindromeString {
static boolean isPalindrome(String str) {
// 2 variable to traverse from left and right
int i = 0;
int j = str.length() - 1;
while(i < j) {
char c1 = str.charAt(i);
char c2 = str.charAt(j);
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we can check lowercase as well
// Above is JDK instruction
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if(u1 != u2 && Character.toLowerCase(u1) != Character.toLowerCase(u2)) {
return false;
}
i++;
j--;
}
return true;
}
public static void main (String[] args) {
String str = "Nadan";
System.out.println(str + " is palindrome : " + isPalindrome(str));
str = "Raghav";
System.out.println(str + " is palindrome : " + isPalindrome(str));
}
}
Comments
Post a Comment