If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if a string is a palindrome, you need to verify whether it reads the same forward and backward. In other words, the characters of the string should be the same when read from left to right and from right to left. Here's a Java method to check for a palindrome:
javaCopy code
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
// Remove spaces and convert the string to lowercase
str = str.replaceAll("\\s", "").toLowerCase();
// Initialize pointers for the first and last characters
int left = 0;
int right = str.length() - 1;
// Compare characters from both ends until the pointers meet
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String str1 = "racecar";
String str2 = "hello";
if (isPalindrome(str1)) {
System.out.println(str1 + " is a palindrome.");
} else {
System.out.println(str1 + " is not a palindrome.");
}
if (isPalindrome(str2)) {
System.out.println(str2 + " is a palindrome.");
} else {
System.out.println(str2 + " is not a palindrome.");
}
}
}
In this example, we have a method isPalindrome
that takes a string str
as input and returns true
if it is a palindrome, and false
otherwise. The method first removes spaces and converts the string to lowercase using the replaceAll()
and toLowerCase()
methods.
We then initialize two pointers left
and right
, pointing to the first and last characters of the string, respectively. We compare the characters at these pointers, and if they are not the same, we return false
.
The comparison continues until the pointers meet in the middle of the string. If all characters are the same during the comparison, the string is a palindrome, and we return true
.
In the main
method, we test the isPalindrome
method with two sample strings. If a string is a palindrome, it will print "<string> is a palindrome." Otherwise, it will print "<string> is not a palindrome."
Example output:
csharpCopy code
racecar is a palindrome.
hello is not a palindrome.
Comments: 0