In: Computer Science
A palindrome is a word or a phrase that is the same when read both forward and backward. Examples are: "bob," "sees," or "never odd or even" (ignoring spaces). Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome.
Ex: If the input is:
bob
the output is:
bob is a palindrome
Ex: If the input is:
bobby
the output is:
bobby is not a palindrome
Hint: Start by just handling single-word input, and submit for grading. Once passing single-word test cases, extend the program to handle phrases. If the input is a phrase, remove or ignore spaces.
IN JAVA
import java.util.Scanner;
public class LabProgram {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
boolean flag = true;
// i is the starting index of the string s
// j is the ending index of the string s
int i = 0, j = s.length()-1;
// Checking the value if character at index i with the character at index j
// If characters match, then move i to its next position and j t its previous position
// If characters does not match then the string is not a palindrome.
// In the case of does not match update the value of flag to false and break the loop
while(i<j){
if(s.charAt(i)==' '){
i++;
}
else if(s.charAt(j)==' '){
j--;
}
else {
if(s.charAt(i)!=s.charAt(j)){
flag = false;
break;
}
i++;
j--;
}
}
if (flag) {
System.out.println(s+" is a palindrome");
} else {
System.out.println(s+" is not a palindrome");
}
}
}

