Search code examples
javastringpalindrome

WHats wrong with this code for palindrome of a string array


Write a method isPalindrome that accepts an array of Strings as its argument and returns true if that array is a palindrome (if it reads the same forwards as backwards) and /false if not. For example, the array {"alpha", "beta", "gamma", "delta", "gamma", "beta", "alpha"} is a palindrome, so passing that array to your method would return true. Arrays with zero or one element are considered to be palindromes.

    public boolean  isPalindrome(String[] str){
        for (int i =0;i<str.length;i++){
           if (str[i]!=str[str.length-1-i])
                return false;
      }
     return true;
     }

It fails for the inputs according to a practice website answers.

isPalindrome({"aay", "bee", "cee", "cee", "bee", "aay"})

isPalindrome({"aay", "bee", "cee", "cee", "bee", "aay"})


Solution

  • str is an array of Strings.

    To compare the value of Strings, you have to use String.equals - the == operator compares the identity of the string and not the value itself.

    public boolean isPalindrome(String[] str){ for (int i=0;i<str.length;i++){ if (!str[i].equals(str[str.length - i - 1])) return false; } return true; }