-1
votes

Impossible d'exécuter le programme Palindrome en Java

Voici mon code Java pour trouver un palindrome d'une chaîne. Il montre o / p comme "Palindrome" même si le i / p que j'ai entré ne l'est pas. Quelqu'un peut-il aider s'il vous plait.

String a = sc.next();
char b[] = a.toCharArray();
char d[] = b;
int size = a.length();
int beg=0,end=size-1;

while(beg<=end)
{
    char temp = b[beg];
    b[beg] = b[end];
    b[end] = temp;
    beg++;
    end--;
}

 if(d.equals(b))
    {
     System.out.print("Palindrome");
    }
else
    System.out.print("Not a Palindrome");


1 commentaires

Est-ce que cela répond à votre question? Vérifiez la chaîne pour le palindrome


3 Réponses :


1
votes

Il y a quelques problèmes avec votre implémentation. Tout d'abord -

    Scanner sc = new Scanner(System.in);
    String a = sc.next();

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

    System.out.println(palindrome ? "Palindrome" : "Not Palindrome");

Déboguez soigneusement et voyez si vous avez vraiment d [] comme l'inverse de b [] à la fin de cette boucle while

Deuxièmement,

    Scanner sc = new Scanner(System.in);
    String a = sc.next();
    String aRev = new StringBuilder(a).reverse().toString();


    if (a.equals(aRev)) {
        System.out.print("Palindrome");
    } else {
        System.out.print("Not a Palindrome");
    }

Ce n'est pas la bonne façon de comparer si tous les éléments du tableau sont identiques dans les deux du tableau. Si vous examinez l'implémentation ou essayez avec un exemple de tableau, vous pourrez le voir vous-même.

Pour vérifier le palindrome, une approche très simple consiste à inverser la chaîne en utilisant StringBuilder et à vérifier si elle est égale à la chaîne d'origine -

 if(d.equals(b))
    {
     System.out.print("Palindrome");
    }

Une autre meilleure approche consiste à exécuter une boucle du début au milieu de la chaîne et à conserver un index de la fin au milieu. Vérifiez ensuite l'index avant et l'index arrière.

while(beg<=end)
{
    char temp = b[beg];
    b[beg] = b[end];
    b[end] = temp;
    beg++;
    end--;
}


0 commentaires

0
votes

Essayez ce code, il fonctionne comme prévu.

String Non-palindrome is palindrome: false
String WoW is palindrome: true

Lorsqu'il est exécuté, le code ci-dessus génère:

public class Main {
    public static boolean isPalindrome(String str) {
        int i = 0, j = str.length() - 1;

        // The following condition checks if the decreasing index 
        // is larger than the increasing one, 
        // which happens at the middle of the string.
        // This is done, because there is no need to iterate over,
        // the entire string.
        while(j > i){ // Non-matching character found, return early.
            if(str.charAt(i) != str.charAt(j)){
                return false;
            }
            j--; // Ending index decreases.
            i++; // Starting index increases.
        }
        // If the loop finishes, without returning all characters of the string match.
        return true;
    }
    public static void main(String[] args) {
        String string = "Non-palindrome";
        String palindrome = "WoW";
        System.out.println("String " + string + " is palindrome: " + isPalindrome(string));
        System.out.println("String " + palindrome + " is palindrome: " + isPalindrome(palindrome));
    }
}


0 commentaires

0
votes

Avec

char d[] = b;

vous créez l'alias d pour b . Donc, en substance, b et d font référence au même char -Array. Il n'y a aucune différence entre la modification de b et la modification de d . Par conséquent, la comparaison d.equals(b) donnera toujours true .


0 commentaires