Search code examples
javastringpalindrome

Generate palindrome words


So, I have this code which generates palindrome words in a special manner. 1> it joins the word by its reverse(excluding last character). 2> the words which end with repeated alphabets, for example ABB becomes ABBA and not ABBBA and XAZZZ becomes XAZZZAX. I am already done with the first part. I have just tried second one by extracting last two characters, because to be honest, I don't know how should I do it.

import java.io.*;
class ISC_Q3_2019
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        ISC_Q3_2019 ob = new ISC_Q3_2019();
        System.out.println("Enter your sentence");
        String s = br.readLine();
        s=s.toUpperCase();
        String words[] = s.split(" ");
        int l=words.length;
        char ch1=s.charAt(s.length()-1);
        String ans=" ", copy=" ", p=" ";
        if(ch1=='.'||ch1=='!'||ch1=='?')
        {
            for(int i=0;i<l;i++)
            {
                if(ob.isPalindrome(words[i])==true)
                {
                    ans=ans+words[i];
                }
                else
                {
                    copy=words[i];
                    words[i]=ob.Reverse(words[i]);
                    p=copy.concat(words[i]);
                    ans=ans+p;
                }
            }
            System.out.println("OUTPUT:" +ans.trim());
        }
        else
            System.out.println("Invalid Input!");
    }
    boolean isPalindrome(String s)
    {
        s=s.toUpperCase();
        int l=s.length();
        char ch;
        String rev=" ", copy=" ";
        copy=s;
        for(int i=l-1;i>=0;i--)
        {
            ch=s.charAt(i);
            rev=rev+ch;
        }
        if(rev.equals(copy))
            return true;
        else
            return false;
    }
    String Reverse(String s)
    {
        s=s.toUpperCase();
        int l=s.length();
        char ch, ch1, ch2;
        String r=" ";
        for(int i=l-2;i>=0;i--)
        {
            ch=s.charAt(i);
            ch1=s.charAt(l-1);
            ch2=s.charAt(l-2);
            if(ch1==ch2)
                r=r+ch;
            else
                r=r+ch;
            }
        return r;
    }
}

OUTPUT:

Enter your sentence The abb is flying.

**OUTPUT:**THE HTABB BAIS IFLYING. GNIYLF

And another part I am concerned is the unmatched spaces.


Solution

  • Here you go

    import java.util.Arrays;
    import java.util.List;
    import java.util.Scanner;
    import java.util.stream.Collectors;
    
    public class Palindrome {
        public static void main(String... args) {
            // Request for input
            Scanner reader = new Scanner(System.in);
            System.out.println("Enter your sentence...");
    
            // Read the user input
            String sentence = reader.nextLine();
    
            // Split the sentence (into tokens) at spaces and special characters using regex
            // Keep the special characters where they are and form a List with the split words
            List<String> tokens = Arrays.asList(sentence.split("((?<=[\\?,\\. ])|(?=[\\?,\\. ]))"));
    
            // For every token/word, form the palindrome of that and then join them back
            String result = tokens.stream().map(s -> formPalindrome(s)).collect(Collectors.joining());
    
            // This is the final result
            System.out.println("result: " + result);
    
            reader.close();
        }
    
        private static String formPalindrome(String str) {
            // Reverse the String
            String reversed = new StringBuilder(str).reverse().toString();
    
            // String length
            int strLen = reversed.length();
    
            // Compare each character of reversed string with last character of the string until they are different
            // When they are different concat the substring with original string
            for (int i = 0; i < strLen; i++) {
                if (reversed.charAt(i) != str.charAt(strLen - 1)) {
                    return str + reversed.substring(i);
                }
            }
    
            return str;
        }
    }