-1

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.

Mikev
  • 2,012
  • 1
  • 15
  • 27
Vishwa Patel
  • 5
  • 1
  • 7

2 Answers2

0

Here is an idea* that you can build on to get the desired result:

  1. Check the original Strings characters in reverse and count how many occurences there are

  2. Create a new String from the start of the original String, up to the end less the count of occurences

  3. Reverse that new String

  4. Concatenate the original String with the new String

So a quickly thrown together example:

int count = 0;
for (int i = s.length() - 1; i > 0; i--) {
    if (s.charAt(i) == s.charAt(i - 1)) {
        count++;
    } else {
        break;
    }
}
StringBuilder sb = new StringBuilder(s.substring(0, s.length() - 1 - count)).reverse();
System.out.println(s + sb.toString());

Which would give "ABBA" for "ABB" and "XAZZAX" for "XAZZZ".

* It's only an idea and there are probably edge cases etc that aren't catered for but it's merely to give the OP an idea of how to approach it

achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • Can you explain what is String builder function? I guess your code will work for me. But just do explain the function please? – Vishwa Patel Feb 15 '19 at 08:02
  • @VishwaPatel it’s juat a Java class - see the docs here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html – achAmháin Feb 15 '19 at 08:08
  • The string builder method works but the output is like Enter your sentence The abb is flying. OUTPUT: THETHEHT ABBABBA ISISI FLYING.FLYING.GNIYLF – Vishwa Patel Feb 15 '19 at 10:10
  • @VishwaPatel as I mentioned in the post, it’s just an idea to get you going. You’ll probably need to tailor it to your specific needs - the post just shows how to work with an individual `String`. – achAmháin Feb 15 '19 at 10:21
0

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;
    }
}
Prasann
  • 1,263
  • 2
  • 11
  • 18
  • your code works perfectly but please suggest me edits in the main() method. The output comes like:- Enter your sentence The abb is flying. OUTPUT: THETHEHT ABBABBA ISISI FLYING.FLYING.GNIYLF – Vishwa Patel Feb 15 '19 at 10:05
  • @VishwaPatel - What would be your expected output? – Prasann Feb 15 '19 at 10:51
  • I have edited it now. Is this what you are expecting? `The abb is flying.` becomes `ThehT abba isi flyingniylf.` – Prasann Feb 15 '19 at 11:11
  • Actually that is my expected output but can you please explain what have you done in String result and the statement right above it because I clearly have no idea about arraylists? – Vishwa Patel Feb 15 '19 at 15:33
  • Did the program work for you? I have now added comments inline explaining what each statement is for. Hope this helps – Prasann Feb 15 '19 at 15:57