Explain how the palindrome example below is the code work Pl
Explain how the palindrome example (below is the code) work. Please explain it properly, not short.
import java.util.Scanner;
public class Palindrome {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print(\"Enter a string: \");
String s = input.nextLine();
// The index of the first character in the string
int low = 0;
// The index of the last character in the string
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;
}
low++;
high--;
}
if (isPalindrome)
System.out.println(s + \" is a palindrome\");
else
System.out.println(s + \" is not a palindrome\");
}
}
Solution
import java.util.Scanner;
public class Palindrome
{
/** Main method */
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print(\"Enter a string: \");
String s = input.nextLine();
// The index of the first character in the string
int low = 0;
// The index of the last character in the string
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) //Starting from the left to right.
//Moving from left to right, the comparison will continue till the string exhausts or the pointers crossover.
{
if (s.charAt(low) != s.charAt(high)) //The left side character is compared with right side character, and if they are not equal.
{
isPalindrome = false; //It\'s not a palindrome.
break; //No further comparison is required, as the test fails.
}
low++; //Move forward by one character from the left.
high--; //Move backward by one character from the right.
}
if (isPalindrome) //If the flag isPalindrome is set to true, therefore, the string is a palindrome.
System.out.println(s + \" is a palindrome\");
else //If the flag isPalindrome is set to false, therefore, the string is not a palindrome.
System.out.println(s + \" is not a palindrome\");
}
}
I explained the code here for you, as comments.
The concept is so simple.
Assume the string is of 5 characters.
So, low will hold a value 0, and high will hold a value 4.
The 0 index character is compared with 4 index character.
If they are equal, then the 1 index character is compared with 3 index character.
Now, the left index and right index both will converge and will point to the same middle character.
And if the 2 above steps executes successfully, then its a palindrome. If not its not a palindrome.

