Question

palindrome est un mot, une phrase, un numéro ou une autre séquence d'unités qui peuvent être lues de la même façon dans les deux sens.

Pour vérifier si un mot est un palindrome je reçois le tableau de caractères du mot et de comparer les caractères. Je l'ai testé et il semble fonctionner. Cependant, je veux savoir si elle est juste ou s'il y a quelque chose à améliorer.

Voici mon 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;
    }
}
Était-ce utile?

La solution

Pourquoi ne pas simplement:

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

Exemple:

L'entrée est "andna".
sera de 0 i1 et i2 sera 4.

itération première boucle, nous comparera word[0] et word[4]. Ils sont égaux, donc nous i1 incrément (il est maintenant 1) et décrément i2 (il est maintenant 3).
Donc, nous comparons les N. Ils sont égaux, donc nous i1 incrément (il est maintenant 2) et décrément i2 (il est 2).
Maintenant, I1 et I2 sont égaux (ils sont tous les deux 2), de sorte que la condition de la boucle while n'est plus vrai si les boucle se termine et on retourne vrai.

Autres conseils

Vous pouvez vérifier si une chaîne est un palindrome en le comparant à l'inverse de lui-même:

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

ou pour les versions de Java antérieures à 1.5,

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

EDIT: une analyse très poussée de l'efficacité (ou absence) de cette solution, à la fois en termes de temps et de l'espace. Si vous êtes intéressé par la complexité de calcul de cela et d'autres solutions possibles à cette question, s'il vous plaît lire!

Une version concise, qui ne comporte pas (inefficacement) l'initialisation d'un tas d'objets:

boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
}

Sinon, récursivité .

Pour toute personne qui est à la recherche d'une solution récursive plus courte, pour vérifier si un satisfait chaîne donnée comme un 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));
    }
}

ou même plus court , si vous voulez:

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

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

aussi une autre solution à la recherche:

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

Et voici un complet Java 8 solution de streaming . IntStream fournit tous les index til des chaînes demi-longueur, puis une comparaison dès le début et de la fin est fait.

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

sortie est la suivante:

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

}

Je travaille sur une solution pour une question qui a été marqué comme duplicata de celui-ci. Autant jeter ici ...

La question a demandé une seule ligne pour résoudre ce problème, et je l'ai pris plus que le palindrome littéraire -. Si des espaces, de la ponctuation et les majuscules / minuscules peuvent rejeter le résultat

Voici la solution laide avec une petite classe de test:

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

Désolé que c'est un peu méchant -. Mais l'autre question spécifiée en une ligne

Vérification palindrome pour la première moitié de la chaîne avec le reste, ce cas suppose l'élimination de tous les espaces blancs.

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

Je suis nouveau à java et je prends votre question comme un défi pour améliorer mes connaissances.

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. Si la chaîne est faite de lettres ou pas une seule lettre, il est palindrome.
  2. Dans le cas contraire, comparer les première et dernière lettres de la chaîne.
    • Si les premières et dernières lettres diffèrent, la chaîne n'est pas un palindrome
    • Dans le cas contraire, les première et dernière lettres sont les mêmes. les déposséder de la chaîne, et de déterminer si la chaîne qui reste est un palindrome. Prenez la réponse pour cette chaîne plus petite et l'utiliser comme la réponse pour la chaîne d'origine puis répéter de 1 .

Essayez ceci:

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

Une autre façon utilise tableau de caractères

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

}

Voici mon analyse de la réponse @ Greg: componentsprogramming.com/palindromes


Sidenote: Mais, pour moi il est important de le faire dans un manière générique . Les exigences sont que la séquence est bidirectionnellement iterable et les éléments de la séquence sont comparables à l'aide de l'égalité. Je ne sais pas comment le faire en Java, mais voici une version C ++, je ne sais pas une meilleure façon de le faire pour des séquences bidirectionnelles.

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

Complexité: linéaire à temps,

  • Si I est RandomAccessIterator: étage (N / 2) et comparissons étage (n / 2) * 2 itérations

  • Si I est BidirectionalIterator:              étage (N / 2) et comparissons étage (n / 2) * 2 itérations              plus (3/2) * n itérations pour trouver le milieu (fonction du milieu)

  • stockage: O (1)

  • n Dymamic mémoire allouée


Récemment, j'écrit un programme de palindrome qui n'utilise pas StringBuilder. Une réponse tardive, mais cela pourrait être utile pour certaines personnes.

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

En utilisant la pile, il peut être fait comme ceci

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

}

Incroyable combien de différentes solutions à un tel exist simple problème! En voici un autre.

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;
}
  
      
  • Cette implémentation fonctionne pour les nombres et les chaînes.
  •   
  • Puisque nous ne faisons pas quelque chose, donc il n'y a pas besoin de convertir la chaîne dans le tableau de caractères.
  •   
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;
}
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;
                }

            }
        }
    }

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

Je cherchais une solution qui non seulement travaillé pour palindromes comme ...

  • "Kayak"
  • "Madame"

... mais aussi bien pour ...

  • "Un homme, un plan, un canal, le Panama!"
  • « Est-ce une voiture ou un chat, j'ai vu? »
  • "Non 'x' dans Nixon"

itératives :. Cela a prouvé être une bonne 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;
    }

récursive . Je pense que cette solution ne devrait pas être bien pire que celle itérative. Est-ce un crapy petit peu, nous devons extraire l'étape de nettoyage de la méthode pour éviter procesing unnecesary.

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

Inverser : Cela a été prouvé comme une solution coûteuse

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

Tous les crédits aux gars répondre à ce poste et apportant la lumière au sujet.

Compte tenu pas de lettres dans les mots

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

Vous pouvez vérifier ici palindrome un certain nombre de chaîne dynamique

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

OMI, la manière récursive est la plus simple et la plus claire.

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

ici, en vérifiant le plus grand palindrome dans une chaîne, toujours à partir de 1er car.

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

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

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**

Sortie D: \ Java> java GetAllPalindromes Entrez une chaîne

Bonjour Nitin utilisateur est mon meilleur ami wow!

La réponse est Set est [Nitin, Nitin, wow, wow, iti]

D: \ Java>

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top