user13901407
user13901407

Reputation:

Checking for equality throughout each character of string

I'm trying to build a palindrome. I think I might be overthinking the solution with way too many conditional loops inside my if statement. I'm having trouble trying to update the while loop to check whether it has gone through and checked for equality throughout each character of the string, and to update it. Can someone point me in the right direction, and also how can I do a cleaner job with code?

public class Main {

    public static void main(String[] args) {
        Main main = new Main();

        main.isPalindrome("saippuakivikauppias");
        main.isPalindrome("Hello World");
        main.isPalindrome("Was it a car or a cat I saw");
    }

    private boolean isPalindrome(String word) {

        int first = word.charAt(0);
        int last = word.charAt(word.length() - 1);

        if(word.length() <= 1) {
             return true;
        } else if(word.trim().length() > 1) {
            if(Character.isLetter(first) && Character.isLetter(last)) {
                while(first == last) {
                    first++;
                    last--;
                    //if loop to check if the while loop as gone through the entire string?
                    //update?
                }
            } else {
                return false;
            }


        }

        return false;
    }

}

Upvotes: 1

Views: 51

Answers (1)

Der Keeper
Der Keeper

Reputation: 168

You really overthought this one - you should think a bit more basic about your problem:

A palindrome is a string that is the same read backward and forward -> create a reverse of word and compare to word

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

You could even do this - depending on your coding style - in one line.

Upvotes: 3

Related Questions