Rahul Singh
Rahul Singh

Reputation: 125

How to get the palindrome of a string in Java

Ok.I know there are several other good procedures to check if a string is palindrome or not.
But I am trying this code.The problem is that since I am checking character by character, each time the character matches it prints out
palindrome.

But I want to print palindrome only once.

So is there a way so I can iterate through the loop completely and then the print statement is executed?

import java.util.Scanner;
public class Solution{
public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    String A = scan.next();

    for(int i =0;i<(A.length()/2);i++)
    {
        if(A.charAt(i)==A.charAt(A.length()-i-1))
            System.out.println("palindrome");
        else
            System.out.println("not palindrome");

    }
  }
}

Upvotes: 1

Views: 2971

Answers (4)

The Roy
The Roy

Reputation: 2208

I like all the responses given above. I however, think that your code will have the following issues: 1. It will consider a single character a palindrome.
2. It will not recognize Rotor and rotoR as palindromes.

I have also added code for you to benchmark your method against your file. I think it is very costly. So reconsider using better algorithm.

package algorithms;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class PalindromeAnalysis {

public static void main(String[] args) {
    Path p1 = Paths.get("/Users/droy/var/palindrome.txt");

    Scanner scan = null;
    try {
        scan = new Scanner(p1);
    } catch (IOException e) {
        e.printStackTrace();
    } 

    long st1 = System.currentTimeMillis();
    while (scan.hasNext()){
        String A = scan.next();
        boolean isPalindrome = true;
        try {
                if (A.length() <= 2) throw new Exception("Is not a Palindrome");

                for(int i =0; i<(A.length()/2);i++)
                { 
                    if (A.toUpperCase().charAt(i) != A.toUpperCase().charAt(A.length()-i-1)){
                        throw new Exception("Is not a Palindrome");
                    }
                }
        }
        catch (Exception e) {
            isPalindrome = false;
        }

        if (isPalindrome){
            System.out.println("This is Palindrome : " + A);
        }
        else {
            System.out.println("This is not Palindrome" + A);
        }
    }

    long et1 = System.currentTimeMillis();
    System.out.println("Time it took was:" + (et1 - st1) + " ms");
}
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

I would keep a boolean flag (defaulted to true) and set to false if it isn't. Then check your flag after the loop. Something like,

boolean palindrome = true;
for(int i = 0; i < (A.length() / 2); i++)
{
    if (A.charAt(i) != A.charAt(A.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (palindrome) {
     System.out.println("palindrome");
} else {
    System.out.println("not palindrome");
}

You could write the last part with the ternary (or conditional operator ? :) like

System.out.println(palindrome ? "palindrome" : "not palindrome");

And, you could replace the loop with StringBuilder.reverse() like

boolean palindrome = new StringBuilder(A).reverse().toString().equals(A);

So, it could be a one liner like

System.out.println(new StringBuilder(A).reverse().toString().equals(A) 
       ? "palindrome" : "not palindrome");

Upvotes: 5

Maljam
Maljam

Reputation: 6274

You should track if the string is still valid or not, for example:

boolean palin = true;
for(int i =0 ; i < A.length()/2 ; i++) {
    if(A.charAt(i)!=A.charAt(A.length()-i-1)) {
        palin = false;
        break;
    }
}

if(palin) System.out.println("Is Palindrome");
else System.out.println("Is Not a Palindrome");

Upvotes: 1

Nayuki
Nayuki

Reputation: 18533

In your code, you check front-half characters against back-half characters, and print palindrome/not palindrome on each character.

Instead, you should loop through the whole string, determine if the whole string is a palindrome or not, and then print once at the very end.

Here is a straightforward way to fix your code:

// At the start, we assume the string is a palindrome.
boolean palin = true;

// We loop through the characters, looking for evidence to contradict our
// assumption. Once palin becomes false, it can never become true again.
for(int i =0;i<(A.length()/2);i++)
{
    if(A.charAt(i)!=A.charAt(A.length()-i-1))
        palin = false;
}

// Now the Boolean variable tells us the answer we want.
if (palin) System.out.println("palindrome");
else System.out.println("not palindrome");

Upvotes: 0

Related Questions