bnfw0317
bnfw0317

Reputation: 1

what can cause this particular palindrome a logic error

The following method was written to determine whether its String parameter reads identically left-to-right and right-to-left (the so called palindrome). I am having trouble finding the logic error of this palindrome. I believe the error is that the two conditions in the whole loop can affect checking the characters in the string. Please correct me if I am wrong so I can propose a proper solution.

enter image description here

This may be a stupid question to many of you, but I am new to java programming and this is written question on paper not actual code if that makes sense.

Upvotes: 0

Views: 425

Answers (3)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

Your logic will only work if the length of input string is an odd number, i.e. 1,3,5 etc. Because in case the length is even, i will never be equal to j. Example for a string "abba":

while (i == j && S.charAt(i) == S.charAt(j)) { // i = 0, j = 3
        i++;
        j--;
    }

iteration-2:

while (i <= j && S.charAt(i) == S.charAt(j)) { // i = 1 , j = 2
        i++;
        j--;
    }

iteration-3:

while (i <= j && S.charAt(i) == S.charAt(j)) { // i = 2 , j = 1
            i++;
            j--;
        }

This will finally result in StringIndexOutOfBoundsException when i reaches negative value and j reaches a value greater than length of string.

Try below code:

  static boolean isPalidrome(String s) {
    int i = 0;
    int j = s.length() - 1;

    while( i <= j && s.charAt(i) == s.charAt(j)) {
      i ++;
      j--;
    }
    return i >= j;
  }

Upvotes: 1

BishalG
BishalG

Reputation: 1434

You may apply following changes in your own code. There are basically two changes which are in your termination condition of while loop i.e. i <= j and return condition of (i >= j)

public static boolean isPalindrome(String S) {
    int i = 0, j = S.length() - 1;
    while (i <= j && S.charAt(i) == S.charAt(j)) {
        i++;
        j--;
    }
    return (i >= j);
}

Upvotes: 0

prasannajoshi
prasannajoshi

Reputation: 157

your code will fail if input string is something like "zz" or "xxxx" meaning even length with same characters so ideally you can try with something like this :

public static boolean isPal(String str) {
        int start = 0;
        int end = str.length() - 1;
        while (start < end) {
            final char f = str.charAt(start++);
            final char b = str.charAt(end--);
            if (f != b) {
                return false;
            }
        }
        return true;
    }

Upvotes: 0

Related Questions