Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me that whether the below code is correct or need some improvement? I was trying to implement palindrome of a string using Java.

public class Intellipaat {

    public static void main(String[] args) {

        String wort = "Intellipaat";

        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;

    }

}

1 Answer

0 votes
by (26.7k points)
edited by

You can use the below code, which is very simple:

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;

}

I hope this will help.

Want to become a Java Expert? join Java Training now!!

Want to know more about Java? Watch this video on Java Tutorial | Java Course :

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Jul 9, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...