3

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
Sara
  • 113
  • 1
  • 1
  • 8

2 Answers2

4

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;
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
2

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; 
}
Eran
  • 387,369
  • 54
  • 702
  • 768