Sara
Sara

Reputation: 123

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

Upvotes: 3

Views: 449

Answers (2)

Sweeper
Sweeper

Reputation: 271115

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;
}

Upvotes: 4

Eran
Eran

Reputation: 393791

Add a boolean flag that tracks whether you already found a mismatching pair of characters:

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

Upvotes: 2

Related Questions