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.