Find Missing Letter in Palindrome - Java - Spicy Coders

Recent

Saturday, July 15, 2017

Find Missing Letter in Palindrome - Java

A string which is a palindrome but has one letter missing will be passed as input. The 
program must print the missing letter.

Example Input and Output:

If the input is madm the output must be madam

If the input is abcdcb the output must be abcdcba

If the input is mikkm the output must be mikkim

Boundary Conditions: The length of the string will be between 2 and 100.

Input Format: The string will be passed as a single line/input argument via the standard input.

Output Format: The missing letter must be printed to the standard console.

Coding:

import java.util.*;
public class Hello {

    public static void main(String[] args) {
                        Scanner sc=new Scanner(System.in);
                        String s=sc.next();
                        char[] c=s.toCharArray();
                        int i=0,j=0;
                        for(i=0,j=c.length-1;i<c.length/2;i++,j--)
                        {
                            if(c[i]!=c[j])
                            {
                                if(c[i]==c[j-1]&&(i!=j-1))
                                {
                                    System.out.print(c[j]);
                                    break;
                                }
                                else{
                                    System.out.print(c[i]);
                                    break;
                                }
                            }
                        }
            }
}

1 comment: