Check if the given string is palindrome

Upasana | September 09, 2019 | 2 min read | 575 views | Java Coding Challenges


In this article we will write java code to check if the given input string is palindrome or not.

Palindrome

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar or the number 10801.

If you are looking for palindrome checker for number instead of a string, then you can follow this article.

Approach

We can take the input string and start comparing its characters using String.charAt(index) from head (first) and tail (last).

  1. If the first character at head is not equal to last char at tail then it is not a palindrome.

  2. If the first character is equal to character at tail we start evaluating the next set of characters, moving the head up by one, and the tail down by one. if all the characters match till head is less than tail, then input string is palindrome.

String Palindrome Checker
public boolean isPalindrome(String input) {
    int head = 0;
    int tail = input.length() - 1;
    while (head < tail) {
        if (input.charAt(head) != input.charAt(tail)) {
            return false;
        }
        head++;
        tail--;
    }
    return true;
}

A slightly compact version of the above implementation would like like below:

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

Unit Testing

we can write unit tests for the recently developed palindrome method. Here we will use Gradle + JUnit5 + Kotlin for writing unit test cases.

We will cover the below test scenarios:

  1. Check a palindrome string

  2. Check non-palindrome string

  3. Check null input for proper behavior

  4. Use CSV of values (valid and invalid) and test if each of them is palindrome

Unit test cases for Palindrome
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource

class PalindromeCheckerTest {

    @Test
    fun `check a palindrome string`() {
        val checker = PalindromeChecker()
        assertEquals(true, checker.isPalindrome("madam"))
    }

    @Test
    fun `check a non-palindrome string`() {
        val checker = PalindromeChecker()
        assertEquals(false, checker.isPalindrome("namste"))
    }

    @Test
    fun `check null input for palindrome`() {
        val checker = PalindromeChecker()
        val exception = assertThrows<IllegalArgumentException> {
            checker.isPalindrome(null)
        }
        assertEquals("must be supplied a valid input string", exception.message)
    }

    @ParameterizedTest(name = "{0} = {1}")
    @CsvSource(
        "madam,   true",
        "racecar, true",
        "108012,  false",
        "hello,   false"
    )
    fun `csv palindrome checker`(first: String, expectedResult: Boolean) {
        val calculator = PalindromeChecker()
        assertEquals(expectedResult, calculator.isPalindrome(first)) {
            if (expectedResult) {
                "$first is not a palidrome"
            } else {
                "$first is a palidrome"
            }
        }
    }
}

Testcases are mostly self explanatory.

You can download sample project from Github

https://github.com/cancerian0684/junit5-gradle-kotlin-sample


Top articles in this category:
  1. Check whether given number is even or odd
  2. Palindrome checker in Java
  3. Find longest non-repeating substring from a given string in Java
  4. Create anagram buckets from a given input array of words
  5. Java Coding Problems for SDET Automation Engineer
  6. Anagrams string checker in Java
  7. Prime number checker in Java

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.