PHZE OXIDE
PHZE OXIDE

Reputation: 549

Can you help me explain this piece of code

I understand the charAt part, but the other part i'm having some trouble with. The rest of this code can you explain this to me step by step, so i understand it more clearly. Thanks

public static boolean y(String str) {
    int i = 0;
    int j = str.length()-1;
    while (i != j && (j - i) != 1) {
        if (str.charAt(i) != str.charAt(j)) 
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

opps i made an error the while statement is suppose to be this >> while (i != j && (j - 1) ! = 1)

Upvotes: 1

Views: 142

Answers (2)

David Grant
David Grant

Reputation: 14243

The code will determine whether or not str is a palindrome.

i will represent each character from the beginning to the middle of the string. j will represent each character from the end to the middle of the string.

You initialise i by setting the value to 0 (the first character). j is initialised to be the length of the string minus 1 (the last character).

Your code then loops, comparing the characters represented by i and j until they don't match, or until there are no characters left to compare.

For example, given the palindrome "radar`, the code could compare:

  • r with r
  • a with a

and then terminate. In odd-length palindromes, there is obviously no need to compare the middle character, hence the i != j in your while statement.

You have a problem in your code when dealing with even-length palindromes. i and j will cross-over, but never be the same. The second clause, (j - i) != 1, appears to be designed to fix this, but it makes the comparison too soon!

Given the palindrome, "pullup", when i is 2 and j is 3 (i.e. both Ls), you will exit the loop without comparing. This means a non-palindromic even word will return true, when it ought to return false.

If you change the entire where clause to:

where (j - i > 0)

Your code will work for all cases.

Upvotes: 5

Jensen Ching
Jensen Ching

Reputation: 3164

It's comparing the beginning of a String (position i) with the end of a String (position j), then traversing to the next pair of characters (i + 1, j - 1) until it reaches the middle of the String, to see if the String is a palindrome.

Upvotes: 1

Related Questions