22

I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations

2
  • 1
    stackoverflow.com/questions/248161/… Commented Dec 9, 2011 at 11:22
  • 1
    @Andy : That is to detect the efficiency of the same. I want the code in the simplest way with least number of line of codes and methods used!! Commented Dec 9, 2011 at 11:26

11 Answers 11

122

Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

boolean isPalindrome(String s) { int n = s.length(); for (int i = 0; i < (n/2); ++i) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } } return true; } 
Sign up to request clarification or add additional context in comments.

12 Comments

Probably the fastest solution executionwise.
Can this solution be altered to take a character as input rather than a string? I am searching for the same palindrome solution but with character input. Also can I ask if the For loop is indeed checking each character from either half of the string and comparing them? Thanks
A single character is always a palindrome.
you don't need to compare the centre character when the length is odd. So you can simply have : for (int i=0;i<(n / 2);++i)
This is close, but wouldn't whitespace or punctuation mess it up? Should you clean the string first?
|
26

For the least lines of code and the simplest case

if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome. 

1 Comment

Very nice, but removal of spaces might be a better deal: return str.replaceAll("\\s", "").equals(new StringBuilder(str.replaceAll("\\s", "")).reverse().toString())+""; `
12

Here is a simple one"

public class Palindrome { public static void main(String [] args){ Palindrome pn = new Palindrome(); if(pn.isPalindrome("ABBA")){ System.out.println("Palindrome"); } else { System.out.println("Not Palindrome"); } } public boolean isPalindrome(String original){ int i = original.length()-1; int j=0; while(i > j) { if(original.charAt(i) != original.charAt(j)) { return false; } i--; j++; } return true; } } 

Comments

8

You can try something like this :

 String variable = ""; #write a string name StringBuffer rev = new StringBuffer(variable).reverse(); String strRev = rev.toString(); if(variable.equalsIgnoreCase(strRev)) # Check the condition 

2 Comments

You could also replace ^[a-z] so this would work with palindromes like "Madam, I'm Adam."
@Alex K, if you don't worry about case-sensitivity, then your sentence is a palindrome. ;-)
7

Here's a good class :

public class Palindrome { public static boolean isPalindrome(String stringToTest) { String workingCopy = removeJunk(stringToTest); String reversedCopy = reverse(workingCopy); return reversedCopy.equalsIgnoreCase(workingCopy); } protected static String removeJunk(String string) { int i, len = string.length(); StringBuffer dest = new StringBuffer(len); char c; for (i = (len - 1); i >= 0; i--) { c = string.charAt(i); if (Character.isLetterOrDigit(c)) { dest.append(c); } } return dest.toString(); } protected static String reverse(String string) { StringBuffer sb = new StringBuffer(string); return sb.reverse().toString(); } public static void main(String[] args) { String string = "Madam, I'm Adam."; System.out.println(); System.out.println("Testing whether the following " + "string is a palindrome:"); System.out.println(" " + string); System.out.println(); if (isPalindrome(string)) { System.out.println("It IS a palindrome!"); } else { System.out.println("It is NOT a palindrome!"); } System.out.println(); } } 

Enjoy.

1 Comment

public boolean isPalindrone (String checkPalindrome) { int length = checkPalindrome.length(); int mid = length/2; int i,j=0; for (i=0, j=length-1; i < mid ; i++, j--) { if (checkPalindrome.charAt(i) != checkPalindrome.charAt(j)) break; } if (i == mid) return true; else return false; }
3
 public boolean isPalindrom(String text) { StringBuffer stringBuffer = new StringBuffer(text); return stringBuffer.reverse().toString().equals(text); } 

Comments

2

I guess this is simple way to check palindrome

String strToRevrse = "MOM"; strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString()); 

Comments

1

I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:

import java.util.ArrayList; import java.util.List; public class PalindromeRecursiveBoolean { public static boolean isPalindrome(String str) { str = str.toUpperCase(); char[] strChars = str.toCharArray(); List<Character> word = new ArrayList<>(); for (char c : strChars) { word.add(c); } while (true) { if ((word.size() == 1) || (word.size() == 0)) { return true; } if (word.get(0) == word.get(word.size() - 1)) { word.remove(0); word.remove(word.size() - 1); } else { return false; } } } } 
  1. If the string is made of no letters or just one letter, it is a palindrome.
  2. Otherwise, compare the first and last letters of the string.
    • If the first and last letters differ, then the string is not a palindrome
    • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.

The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'

Comments

0

check this condition

String string="//some string...//"

check this... if(string.equals((string.reverse()) { it is palindrome }

1 Comment

String does not have a reverse method.
0
public static boolean istPalindrom(char[] word){ int i1 = 0; int i2 = word.length - 1; while (i2 > i1) { if (word[i1] != word[i2]) { return false; } ++i1; --i2; } return true; } 

1 Comment

Duplicated from here stackoverflow.com/a/4138856/1740354. Mentioning the source would be a good idea.
0
import java.util.Scanner; public class FindAllPalindromes { static String longestPalindrome; public String oldPalindrome=""; static int longest; public void allSubstrings(String s){ for(int i=0;i<s.length();i++){ for(int j=1;j<=s.length()-i;j++){ String subString=s.substring(i, i+j); palindrome(subString); } } } public void palindrome(String sub){ System.out.println("String to b checked is "+sub); StringBuilder sb=new StringBuilder(); sb.append(sub); // append string to string builder sb.reverse(); if(sub.equals(sb.toString())){ // palindrome condition System.out.println("the given String :"+sub+" is a palindrome"); longestPalindrome(sub); } else{ System.out.println("the string "+sub+"iss not a palindrome"); } } public void longestPalindrome(String s){ if(s.length()>longest){ longest=s.length(); longestPalindrome=s; } else if (s.length()==longest){ oldPalindrome=longestPalindrome; longestPalindrome=s; } } public static void main(String[] args) { FindAllPalindromes fp=new FindAllPalindromes(); Scanner sc=new Scanner(System.in); System.out.println("Enter the String ::"); String s=sc.nextLine(); fp.allSubstrings(s); sc.close(); if(fp.oldPalindrome.length()>0){ System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome"); } else{ System.out.println(longestPalindrome+":is the longest palindrome`````"); }} } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.