Check string for palindrome

A palindrome is a word, phrase, number, or other sequence of units that can be read the same in any direction.

To check if a word is a palindrome, I get a char array of that word and compare the characters. I tested it and it seemed to work. However, I want to know if this is right or something to improve.

Here is my code:

public class Aufg1 { public static void main(String[] args) { String wort = "reliefpfpfeiller"; char[] warray = wort.toCharArray(); System.out.println(istPalindrom(warray)); } public static boolean istPalindrom(char[] wort){ boolean palindrom = false; if(wort.length%2 == 0){ for(int i = 0; i < wort.length/2-1; i++){ if(wort[i] != wort[wort.length-i-1]){ return false; }else{ palindrom = true; } } }else{ for(int i = 0; i < (wort.length-1)/2-1; i++){ if(wort[i] != wort[wort.length-i-1]){ return false; }else{ palindrom = true; } } } return palindrom; } } 
+85
java string arrays char palindrome
Nov 09 '10 at 21:28
source share
36 answers
  • one
  • 2

Why not just:

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

Example:

Entering "andna".
i1 will be 0, and i2 will be 4.

The iteration of the first loop will compare word[0] and word[4] . They are equal, so we increase i1 (now 1) and decrease i2 (now 3).
Therefore, we compare n. They are equal, so we increase i1 (now 2) and decrease i2 (this is 2).
Now i1 and i2 are equal (they are both equal 2), so the condition for the while loop is no longer true, so the loop ends, and we return true.

+174
Nov 09 '10 at 21:32
source share
โ€” -

You can check if the string is a palindrome by comparing it with the opposite:

 public static boolean isPalindrome(String str) { return str.equals(new StringBuilder(str).reverse().toString()); } 

or for versions of Java earlier than 1.5,

 public static boolean isPalindrome(String str) { return str.equals(new StringBuffer().append(str).reverse().toString()); } 

EDIT: @FernandoPelliccioni provided a very thorough analysis of the effectiveness (or lack) of this solution, both in terms of time and space. If you are interested in the computational complexity of this and other possible solutions to this issue, read it!

+113
Nov 09 '10 at 21:54
source share

A short version that does not include (inefficiently) initializing a bunch of objects:

 boolean isPalindrome(String str) { int n = str.length(); for( int i = 0; i < n/2; i++ ) if (str.charAt(i) != str.charAt(ni-1)) return false; return true; } 
+60
Feb 22 '13 at 6:42
source share

Alternatively, recursion .

For anyone looking for a shorter recursive solution, check to see if a given string satisfies like a palindrome:

 private boolean isPalindrome(String s) { int length = s.length(); if (length < 2) // If the string only has 1 char or is empty return true; else { // Check opposite ends of the string for equality if (s.charAt(0) != s.charAt(length - 1)) return false; // Function call for string with the two ends snipped off else return isPalindrome(s.substring(1, length - 1)); } } 



OR even shorter if you want:

 private boolean isPalindrome(String s) { int length = s.length(); if (length < 2) return true; return s.charAt(0) != s.charAt(length - 1) ? false : isPalindrome(s.substring(1, length - 1)); } 
+16
Oct 30 '16 at 13:39
source share

Go, Java:

 public boolean isPalindrome (String word) { String myWord = word.replaceAll("\\s+",""); String reverse = new StringBuffer(myWord).reverse().toString(); return reverse.equalsIgnoreCase(myWord); } isPalindrome("Never Odd or Even"); // True isPalindrome("Never Odd or Even1"); // False 
+10
Mar 04 '14 at 8:44
source share
 public class Palindromes { public static void main(String[] args) { String word = "reliefpfpfeiller"; char[] warray = word.toCharArray(); System.out.println(isPalindrome(warray)); } public static boolean isPalindrome(char[] word){ if(word.length%2 == 0){ for(int i = 0; i < word.length/2-1; i++){ if(word[i] != word[word.length-i-1]){ return false; } } }else{ for(int i = 0; i < (word.length-1)/2-1; i++){ if(word[i] != word[word.length-i-1]){ return false; } } } return true; } } 
+4
Nov 09 '10 at 21:35
source share

also another solution:

 public static boolean isPalindrome(String s) { for (int i=0 , j=s.length()-1 ; i<j ; i++ , j-- ) { if ( s.charAt(i) != s.charAt(j) ) { return false; } } return true; } 
+4
May 26 '16 at 3:52
source share

And here is the complete Java 8 streaming solution. IntStream provides all indexes with half the length of the rows, and then a comparison is made from the beginning and from the end.

 public static void main(String[] args) { for (String testStr : Arrays.asList("testset", "none", "andna", "haah", "habh", "haaah")) { System.out.println("testing " + testStr + " is palindrome=" + isPalindrome(testStr)); } } public static boolean isPalindrome(String str) { return IntStream.range(0, str.length() / 2) .noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1)); } 

Exit:

 testing testset is palindrome=true testing none is palindrome=false testing andna is palindrome=true testing haah is palindrome=true testing habh is palindrome=false testing haaah is palindrome=true 
+4
May 2 '17 at 6:49
source share

I worked on a solution to a question that was marked as a duplicate of this. You can also drop it here ...

The request was given one line to solve this problem, and I took it as a literary palindrome - so spaces, punctuation and upper / lower case can discard the result.

Here's an ugly solution with a small test class:

 public class Palindrome { public static boolean isPalendrome(String arg) { return arg.replaceAll("[^A-Za-z]", "").equalsIgnoreCase(new StringBuilder(arg).reverse().toString().replaceAll("[^A-Za-z]", "")); } public static void main(String[] args) { System.out.println(isPalendrome("hiya")); System.out.println(isPalendrome("star buttons not tub rats")); System.out.println(isPalendrome("stab nail at ill Italian bats!")); return; } } 

Sorry this is disgusting - but another liner asked another question.

+3
Jun 03 2018-11-11T00:
source share
 public class palindrome { public static void main(String[] args) { StringBuffer strBuf1 = new StringBuffer("malayalam"); StringBuffer strBuf2 = new StringBuffer("malayalam"); strBuf2.reverse(); System.out.println(strBuf2); System.out.println((strBuf1.toString()).equals(strBuf2.toString())); if ((strBuf1.toString()).equals(strBuf2.toString())) System.out.println("palindrome"); else System.out.println("not a palindrome"); } 

}

+3
Feb 08 '13 at 12:50
source share

Checking the palindrome for the first half of the line with the rest, this case involves removing any spaces.

 public int isPalindrome(String a) { //Remove all spaces and non alpha characters String ab = a.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); //System.out.println(ab); for (int i=0; i<ab.length()/2; i++) { if(ab.charAt(i) != ab.charAt((ab.length()-1)-i)) { return 0; } } return 1; } 
+3
Jun 02 '17 at 17:27
source share

I am new to java and I view your question as a problem to improve my knowledge.

 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; } } } } 
  • If a string consists of letters or one letter, it is a palindrome.
  • Otherwise, compare the first and last letters of the string.
    • If the first and last letters are different, the string is not a palindrome
    • Otherwise, the first and last letters are the same. Separate them from the string and determine if the remaining string is a palindrome. Take the answer for this smaller line and use it as the answer for the original line, then repeat from 1 .
+2
Dec 16 '14 at 2:08
source share

Try the following:

 import java.util.*; public class str { public static void main(String args[]) { Scanner in=new Scanner(System.in); System.out.println("ENTER YOUR STRING: "); String a=in.nextLine(); System.out.println("GIVEN STRING IS: "+a); StringBuffer str=new StringBuffer(a); StringBuffer str2=new StringBuffer(str.reverse()); String s2=new String(str2); System.out.println("THE REVERSED STRING IS: "+str2); if(a.equals(s2)) System.out.println("ITS A PALINDROME"); else System.out.println("ITS NOT A PALINDROME"); } } 
+1
Mar 12 '13 at 7:19
source share
 public boolean isPalindrome(String abc){ if(abc != null && abc.length() > 0){ char[] arr = abc.toCharArray(); for (int i = 0; i < arr.length/2; i++) { if(arr[i] != arr[arr.length - 1 - i]){ return false; } } return true; } return false; } 
+1
May 28 '15 at 11:58
source share

Another way: char Array

 public class Palindrome { public static void main(String[] args) { String str = "madam"; if(isPalindrome(str)) { System.out.println("Palindrome"); } else { System.out.println("Not a Palindrome"); } } private static boolean isPalindrome(String str) { // Convert String to char array char[] charArray = str.toCharArray(); for(int i=0; i < str.length(); i++) { if(charArray[i] != charArray[(str.length()-1) - i]) { return false; } } return true; } 

}

+1
Jun 24 '15 at 11:18
source share

Here is my analysis of @Greg's answer: componentsprogramming.com/palindromes




Sidenote: But for me it is important to do this using the General way . The requirements are that the sequence is a bidirectional iteration and the elements of the sequence are comparable using equality. I donโ€™t know how to do this in Java, but, here is the C ++ version, I donโ€™t know how best to do this for bidirectional sequences.

 template <BidirectionalIterator I> requires( EqualityComparable< ValueType<I> > ) bool palindrome( I first, I last ) { I m = middle(first, last); auto rfirst = boost::make_reverse_iterator(last); return std::equal(first, m, rfirst); } 

Difficulty: linear time,

  • If I RandomAccessIterator: gender (n / 2) comparison and gender (n / 2) * 2 iterations

  • If I'm bidirectional, Emulator: gender (n / 2) comparisons and gender (n / 2) * 2 iterations plus (3/2) * n iterations to search for average (middle function)

  • storage: O (1)

  • No dynamic allocation memory




+1
Nov 14 '16 at 14:28
source share

I recently wrote a palindrome program that does not use StringBuilder. Late answer, but it may come in handy for some people.

 public boolean isPalindrome(String value) { boolean isPalindrome = true; for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) { if (value.charAt(i) != value.charAt(j)) { isPalindrome = false; } } return isPalindrome; } 
+1
Apr 20 '17 at 6:56
source share

Using the stack, this can be done as follows:

 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str=in.nextLine(); str.replaceAll("\\s+",""); //System.out.println(str); Stack<String> stack=new Stack<String>(); stack.push(str); String str_rev=stack.pop(); if(str.equals(str_rev)){ System.out.println("Palindrome"); }else{ System.out.println("Not Palindrome"); } } } 
+1
Apr 20 '17 at 7:24
source share
  public static boolean isPalindrome(String word) { String str = ""; for (int i=word.length()-1; i>=0; i--){ str = str + word.charAt(i); } if(str.equalsIgnoreCase(word)){ return true; }else{ return false; } } 
+1
May 26 '17 at 12:33
source share

It's amazing how many different solutions there are to such a simple problem! Here is another one.

 private static boolean palindrome(String s){ String revS = ""; String checkS = s.toLowerCase(); String[] checkSArr = checkS.split(""); for(String e : checkSArr){ revS = e + revS; } return (checkS.equals(revS)) ? true : false; } 
+1
Jan 18 '18 at 16:33
source share
  • This implementation works for numbers and strings.
  • Since we are not writing anything, so there is no need to convert the string to an array of characters.
 public static boolean isPalindrome(Object obj) { String s = String.valueOf(obj); for(int left=0, right=s.length()-1; left < right; left++,right--) { if(s.charAt(left++) != s.charAt(right--)) return false; } return true; } 
+1
Dec 02 '18 at 4:06
source share
 import java.util.Scanner; public class Palindrom { public static void main(String []args) { Scanner in = new Scanner(System.in); String str= in.nextLine(); int x= str.length(); if(x%2!=0) { for(int i=0;i<x/2;i++) { if(str.charAt(i)==str.charAt(x-1-i)) { continue; } else { System.out.println("String is not a palindrom"); break; } } } else { for(int i=0;i<=x/2;i++) { if(str.charAt(i)==str.charAt(x-1-i)) { continue; } else { System.out.println("String is not a palindrom"); break; } } } } } 
0
Dec 04 '15 at 5:14
source share
 private static boolean isPalindrome(String word) { int z = word.length(); boolean isPalindrome = false; for (int i = 0; i <= word.length() / 2; i++) { if (word.charAt(i) == word.charAt(--z)) { isPalindrome = true; } } return isPalindrome; } 
0
Oct 24 '16 at 7:43
source share

I was looking for a solution that not only worked for palindromes like ...

  • "Kayak"
  • Madame

... but also for ...

  • "Man, plan, channel, Panama!"
  • "Was it the car or the cat I saw?"
  • No x at Nixon

Iterative : This has been proven as a good solution.

 private boolean isPalindromeIterative(final String string) { final char[] characters = string.replaceAll("[\\W]", "").toLowerCase().toCharArray(); int iteratorLeft = 0; int iteratorEnd = characters.length - 1; while (iteratorEnd > iteratorLeft) { if (characters[iteratorLeft++] != characters[iteratorEnd--]) { return false; } } return true; } 

Recursive . I think this solution should not be much worse than iterative. We need a little therapy in order to extract the cleansing step from the method in order to avoid an unnecessary process.

 private boolean isPalindromeRecursive(final String string) { final String cleanString = string.replaceAll("[\\W]", "").toLowerCase(); return isPalindromeRecursiveRecursion(cleanString); } private boolean isPalindromeRecursiveRecursion(final String cleanString) { final int cleanStringLength = cleanString.length(); return cleanStringLength <= 1 || cleanString.charAt(0) == cleanString.charAt(cleanStringLength - 1) && isPalindromeRecursiveRecursion (cleanString.substring(1, cleanStringLength - 1)); } 

Reverse : This has been proven as an expensive solution.

 private boolean isPalindromeReversing(final String string) { final String cleanString = string.replaceAll("[\\W]", "").toLowerCase(); return cleanString.equals(new StringBuilder(cleanString).reverse().toString()); } 

All loans to the guys who answer this post and bring light to the topic.

0
Oct 24 '16 at 15:51
source share

Given no letters in words

 public static boolean palindromeWords(String s ){ int left=0; int right=s.length()-1; while(left<=right){ while(left<right && !Character.isLetter(s.charAt(left))){ left++; } while(right>0 && !Character.isLetter(s.charAt(right))){ right--; } if((s.charAt(left++))!=(s.charAt(right--))){ return false; } } return true; } 

---

 @Test public void testPalindromeWords(){ assertTrue(StringExercise.palindromeWords("ece")); assertTrue(StringExercise.palindromeWords("kavak")); assertFalse(StringExercise.palindromeWords("kavakdf")); assertTrue(StringExercise.palindromeWords("akka")); assertTrue(StringExercise.palindromeWords("??e@@c_--e")); } 
0
Dec 08 '16 at 7:44
source share

Here you can check palindrome for the number of rows dynamically

 import java.util.Scanner; public class Checkpalindrome { public static void main(String args[]) { String original, reverse = ""; Scanner in = new Scanner(System.in); System.out.println("Enter How Many number of Input you want : "); int numOfInt = in.nextInt(); original = in.nextLine(); do { if (numOfInt == 0) { System.out.println("Your Input Conplete"); } else { System.out.println("Enter a string to check palindrome"); original = in.nextLine(); StringBuffer buffer = new StringBuffer(original); reverse = buffer.reverse().toString(); if (original.equalsIgnoreCase(reverse)) { System.out.println("The entered string is Palindrome:"+reverse); } else { System.out.println("The entered string is not Palindrome:"+reverse); } } numOfInt--; } while (numOfInt >= 0); } } 
0
Dec 23 '16 at 17:43
source share

IMO, the recursive path is the simplest and clearest.

 public static boolean isPal(String s) { if(s.length() == 0 || s.length() == 1) return true; if(s.charAt(0) == s.charAt(s.length()-1)) return isPal(s.substring(1, s.length()-1)); return false; } 
0
Jan 08 '17 at 21:45
source share

here, checking the largest palindrome in the string, always starting at 1st char.

 public static String largestPalindromeInString(String in) { int right = in.length() - 1; int left = 0; char[] word = in.toCharArray(); while (right > left && word[right] != word[left]) { right--; } int lenght = right + 1; while (right > left && word[right] == word[left]) { left++; right--; } if (0 >= right - left) { return new String(Arrays.copyOf(word, lenght )); } else { return largestPalindromeInString( new String(Arrays.copyOf(word, in.length() - 1))); } } 
0
Feb 03 '17 at 16:21
source share

Code snippet:

 import java.util.Scanner; class main { public static void main(String []args) { Scanner sc = new Scanner(System.in); String str = sc.next(); String reverse = new StringBuffer(str).reverse().toString(); if(str.equals(reverse)) System.out.println("Pallindrome"); else System.out.println("Not Pallindrome"); } } 
0
Mar 28 '17 at 18:23
source share

enter image description here

 import java.util.Collections; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class GetAllPalindromes { static Scanner in; public static void main(String[] args) { in = new Scanner(System.in); System.out.println("Enter a string \n"); String abc = in.nextLine(); Set a = printAllPalindromes(abc); System.out.println("set is " + a); } public static Set<CharSequence> printAllPalindromes(String input) { if (input.length() <= 2) { return Collections.emptySet(); } Set<CharSequence> out = new HashSet<CharSequence>(); int length = input.length(); for (int i = 1; i < length - 1; i++) { for (int j = i - 1, k = i + 1; j >= 0 && k < length; j--, k++) { if (input.charAt(j) == input.charAt(k)) { out.add(input.subSequence(j, k + 1)); } else { break; } } } return out; } } **Get All Palindrome in s given string** 

Exit D: \ Java> java GetAllPalindromes Enter a string

Hi, nitin user is my best friend wow!

Answer set [nitin, nitin, wow, wow, iti]

D: \ Java>

0
Jun 12 '17 at 9:15 on
source share
  • one
  • 2



All Articles