-6

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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Srk95
  • 139
  • 1
  • 8
  • 1
    Please first do some research, there are plenty of other questions here at SO regarding finding palindromes. – Zabuzard Sep 05 '17 at 09:53
  • 2
    What do you mean by not working? – Adeel Ansari Sep 05 '17 at 09:54
  • 1
    Possible duplicate of [Check string for palindrome](https://stackoverflow.com/questions/4138827/check-string-for-palindrome) – Zabuzard Sep 05 '17 at 09:54
  • 1
    As Zabuza already stated, there are a _lot_ of example for palindrome detection on the net and even on SO. Most of them handle characters but those should be adaptable if you treat individual words as the others treat characters. – Thomas Sep 05 '17 at 09:55
  • 3
    @Zabuza CodeReview is **not** the place to ask if you want to find a bug. StackOverflow is… – 301_Moved_Permanently Sep 05 '17 at 09:56
  • Its giving me blank output, that means not working @AdeelAnsari – Srk95 Sep 05 '17 at 09:56
  • Hint on the first half of your code: have a look at `String.split()`. – Thomas Sep 05 '17 at 09:56
  • FYI : Just saying, but a palindrome, even for a sentence, reverse every character. Not just the word. Like _"Was it a car or a cat I saw?"_ – AxelH Sep 05 '17 at 09:57
  • @Zabuza, I know very well how to check string for palindrome, it's about sentence – Srk95 Sep 05 '17 at 09:58
  • no @AxelH, not like that, I want to check only position and sequence of words like "I love phone love I", that means the sentence should be same when reading from both ends. – Srk95 Sep 05 '17 at 09:59
  • The general procedure would be to **split** on each word boundary (*space* as delimiter for easy sentences, regex `\b` for more complex). Then iterate the list and always check the **i-th** element with the **(length - 1 - i)-th** element. For example the first with the last element, the second with the second to last element and so on. If every check goes through, then its a *sentence-palindrome* (whatever it is called). – Zabuzard Sep 05 '17 at 10:01

4 Answers4

4

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;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

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;
}
0

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);

}
Payal
  • 903
  • 1
  • 9
  • 28
  • Could you also explain how your code works and how it solves the issue of OP? *Code only* answers are often not that helpful. – Zabuzard Sep 05 '17 at 10:05
0

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");
progyammer
  • 1,498
  • 3
  • 17
  • 29