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.

4

There are 4 best solutions below

0
On BEST ANSWER

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");
1
On

As per your problem, Ist element of string should match with last one, 2nd with 2nd last and so on. So, splitting the string based on " " would give you an array of strings. Next step would be to check if Ist and last string are equal and so on. Hence, ps[i].equals(ps[ps.length-1 - i]). If at any point, strings does not match, break the loop and deduce that string is not palindrome. Check this implementation :-

void checkPalindrome() {
    String str = "I LOVE MY COUNTRY INDIA COUNTRY MY LOVE I";
    String[] ps = str.split(" ");
    boolean palindrome = true;

    int center = (int) ps.length / 2;

    for (int i = 0; i < center; i++) {
        if (ps[i].equals(ps[ps.length-1 - i])) {
            palindrome = true;
        } else {
            palindrome = false;
            break;
        }

    }
    System.out.println(palindrome);

}
2
On

if you analyse the issue before start coding you will see:

the string is defined like:

[I, LOVE, MY, COUNTRY, INDIA, COUNTRY, MY, LOVE, I]
[0,  1,   2 ,  3,        4,      5,    6,   7,   8]

so it must be a match on words at index:

0 == 8
1 == 7
2 == 6
....
....

or the sequence

i  == x.size- i - 1 

your code could be simplified to:

private static boolean getPa(String str) {
    String[] list = str.split(" ");
    boolean xc = false;
    for (int i = 0; i < list.length / 2; i++) {
        xc = list[i].equalsIgnoreCase(list[list.length - i - 1]);
        if (!xc) {
            return false;
        }
    }
    return true;
}

or using Collections

private static boolean getPa(String str) {
    List<String> list = Arrays.asList(str.split(" "));
    boolean xc = false;
    for (int i = 0; i < list.size() / 2; i++) {
        xc = list.get(i).equalsIgnoreCase(list.get(list.size() - i - 1));
        if (!xc) {
            return false;
        }
    }
    return true;
}
0
On

In your code, change the flag increment to i+1, as you want to move the flag after the space

if(str.charAt(i)==' ')
{
   list.add(str.substring(flag, i).toString());
   flag=i+1;
}

But your code makes unnecessary checks as you need to only check the String half way through. Also you should break the loop here if there is no match :

while(it1.hasNext() && it2.hasPrevious())
{
    if(it1.next().equals(it2.previous()))
    {
        cnt++;
    }
}

Here's my solution :

public boolean checkPalindrome(String str) {
  String[] words = str.split(" ");
  for (int i = 0; i < words.length / 2; i++) {
      if(!words[i].equals(words[words.length - i - 1]){
          return false;
      }
  }
  return true;
}