We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Java program to check if a given string is a palindrome
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
int len = A.length();
boolean isPalindrome = true;
// Check if the string is a palindrome by comparing characters from both ends
for (int i = 0; i < len / 2; i++) {
if (A.charAt(i) != A.charAt(len - i - 1)) {
isPalindrome = false;
break;
}
}
// Output "Yes" if palindrome, otherwise output "No"
if (isPalindrome) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
This Java program checks whether a given string A is a palindrome efficiently using character comparisons. It iterates through the first half of the string and checks if each character from the start matches its corresponding character from the end. If any characters do not match, it concludes that the string is not a palindrome. The program prints "Yes" if the string is a palindrome and "No" otherwise.
Time complexity : O(n/2).
Hope this helps clarify the problem.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java String Reverse
You are viewing a single comment's thread. Return to all comments →
// Java program to check if a given string is a palindrome import java.io.; import java.util.;
public class Solution {
}
This Java program checks whether a given string A is a palindrome efficiently using character comparisons. It iterates through the first half of the string and checks if each character from the start matches its corresponding character from the end. If any characters do not match, it concludes that the string is not a palindrome. The program prints "Yes" if the string is a palindrome and "No" otherwise.
Time complexity : O(n/2). Hope this helps clarify the problem.