A palindrome is a word that reads the same backward and forward. Given a string
ID: 3927471 • Letter: A
Question
A palindrome is a word that reads the same backward and forward. Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters in front of it. Find the length of the shortest palindrome that you can create from S by applying the above transformation. Your program will take A string S (1 lessthanorequalto Length(S) lessthanorequalto 100) where each character of S will be a lowercase alphabet (Between 'a' to 'z') For each input, print out an integer L denoting the length of the shortest palindrome you can generate from S.Explanation / Answer
import java.util.*;
public class expectopallendrome {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter string to check pallendrom:");
String input=sc.next();
String copys="";
String rev="";
int len=0;
char k='s';
int count=0;
int cont2=0;
int fcount=0;
int fcont2=0;
for(int i=input.length()-1;i>=0;i--)
rev=rev+input.charAt(i);
if(input.equalsIgnoreCase(rev)){
len=rev.length();
System.out.println(len);}
else
{
for(int i=0;i<input.length();i++){
if(input.charAt(i)!=k){
k=input.charAt(i);
count++;}
else{
cont2++;
copys=copys+input.charAt(i);}
}
fcount=count-1;
fcont2=cont2+1;
System.out.println(fcont2+fcount+fcont2);
}
output:
enter string to check pallendrom:
baaa
7
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.