Search code examples
javastringcollectionspalindromelistiterator

How to check in Java whether the input Sentence is of palindrome(not exactly, but like that) in nature or not?


I have a String input as

"I LOVE MY COUNTRY INDIA COUNTRY MY LOVE I".

This is a perfect palindrome sentence as the word sequence exactly matches from start to middle and end to middle.

I want to create a function to prove this using Java. I want to check only position and sequence of words like "I love phone love I", that means the sentence of nature which should be same when reading from both ends. I have tried following code:

void checkPalindrome()
{
    String str = "I LOVE MY COUNTRY INDIA COUNTRY MY LOVE I";
    List<String> list=new ArrayList<String>();
    int i,flag=0,cnt=0;
    for(i=0;i<str.length();i++)
    {
        if(str.charAt(i)==' ')
        {
            list.add(str.substring(flag, i).toString());
            flag=i;
        }
    }list.add(str.substring(flag, i).toString());

    Iterator<String> it1=list.iterator();
    ListIterator<String> it2=list.listIterator(list.size());
    while(it1.hasNext() && it2.hasPrevious())
    {
        if(it1.next().equals(it2.previous()))
        {
            cnt++;
        }
    }
    if(cnt==list.size())
        System.out.println("Palindrome nature found");
}


This is not working by the way, please help me to do it in exact way.


Solution

  • First take the words of str in an array. Then check whether the words in the forward order and the reverse order are same.

    String[] words = str.split(" "); //splits at spaces
    boolean flag = true;
    int i, last = words.length - 1;
    for(i = 0; i <= last/2; i++){
        if(!words[i].equalsIgnoreCase(words[last - i])){
            flag = false;
            System.out.printf("NOT PALINDROME");
            break;
        }
    }
    
    if(flag)
        System.out.printf("PALINDROME");