Is String A Palindrome?

Is String A Palindrome?

2 Comments

Problem

You are given a string and are asked to write a method to return true if the string is a palindrome and to return false otherwise. A palindrome is a string that reads the same from front to back like alula

They are many solutions to check if a string is a palindrome. I’m going to show you three solutions. The first will use a StringBuilder and the second will use a Character Array to solve the problem. For the third solution, we will solve the problem in-place

Solution Using StringBuilder

public boolean isPalindrome(String word) {
    // create string builder
    StringBuilder sb = new StringBuilder(word);
    // reverse string builder and create new string
    String reverseWord = sb.reverse().toString();
    return word.equals(reverseWord);
}

In this solution we:

  1. Create a StringBuilder on line 3.
  2. Reverse the StringBuilder and create a new String on line 5.
  3. Use the equals method to see two strings are the same on line 6.

Solution Using CharArray

 public boolean isPalindrome(String word) {

    // create array
    char[] charArray = word.toCharArray();
    // create two index start and end
    for (int start = 0, end = word.length() - 1; start < end; ++start, --end){
      // check if the two values are  not the same
      if(charArray[start] != charArray[end]) return false;
    }
   return true;
}

In this solution we:

  1. Create a new character array on line 4 using the toCharArray() method.
  2. Loop through the array on line 6.
  3. Check if the two values are not the same on line 8. If the values are not the same we return false.
  4. Return true on line 10.

Solution In-Place

public boolean isPalindrome(String word) {
    // create two index start and end
    for (int start = 0, end = word.length() - 1; start < end; ++start, --end) {
        // check if the two values are not the same
        if (word.charAt(start) != word.charAt(end)) return false;
    }
    return true;
}

This solution is almost the same as the last one but, we use the charAt method to compare the characters. This solution is faster because it loops over the array at most once and does not use more memory.

Conclusion

You have seen different ways to check if a string is a Palindrome or not in this post. If you are asked this question in a technical interview, you will have some solutions under your belt.

 

Originally published at fluentjava.com

About Harrison Brock

Java and Go Software Engineer.

    You May Also Like