1

I know there is an easier way of making things work to check whether a string is a palindrome or not, but I wanted to try it using library functions and I came up with the code below.

public boolean isPalindrome1(String input)
{

    int length = input.length()/2;
    if(input.length()%2!=0)
    {
        length = length + 1;
    }


    return(input.substring(0,length).equals(new StringBuilder(input.substring(length, input.length())).reverse().toString()));
}

I'm trying to check whether half the string is equal to the other half's reverse. But it is getting messed up for odd and even lengths. Can someone point corrections in this where it will work for odd, even lengths as well as empty string and string of length = 1.

7
  • 1
    Why half? You won't get any noticeable performance improvements over the whole string (which avoids the odd/even problem) Commented Aug 2, 2012 at 16:34
  • But with splitting how will it work ? I will not use the code but am just curious to know how to solve for this case. Commented Aug 2, 2012 at 16:41
  • There's no need to solve a hard problem if there's an easier way to do it. "Solving for this case" in my book is using the simple solution. Commented Aug 2, 2012 at 16:49
  • @Phoenix here you go.. look at my answer Commented Aug 2, 2012 at 17:10
  • @SomeKittens you should know each and every possible way to solve a problem Commented Aug 2, 2012 at 17:11

2 Answers 2

6

You're already using reverse(). Why can you not compare the input String with the reverse? Isn't that exactly what you're wanting in the first place? No need to be splitting things in half in a complicated way.

Sign up to request clarification or add additional context in comments.

Comments

2

you can:

return new StringBuilder(input).reverse().toString().equals(input);

here you go as you want to know :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.