Search code examples
javapalindrome

Checking if string has only one character mismatch of palindrome in java


I have to write a boolean function that takes a string and check if a string is a palindrome or not in java.

Here is my code

    static boolean isPalindrome(String input) 
{ 
    int i = 0;
    last = input.length() - 1; 
    while (i < last) { 
        if (input.charAt(i) != input.charAt(last)) 
            return false; 
        i++; 
        last--; 
    } 
    return true; 
}

I want to add this part to my code but I got stuck on that if there is only one character mismatch I should consider it as valid palindrome.

Sample results:

“book” ​-> true
“refer” ​-> true
“” ​​-> true

Solution

  • Instead of immediately returning false when two characters are different, you keep a count of how many pairs of characters are different:

    static boolean isPalindrome(String input)
    {
        int i = 0;
        int last = input.length() - 1;
        int differentCount = 0;
        while (i < last) {
            if (input.charAt(i) != input.charAt(last)) {
                differentCount++;
                // only return false if more than one character is different
                if (differentCount > 1) {
                    return false;
                }
            }
            i++;
            last--;
        }
        return true;
    }