Given a string s, decide whether swapping exactly one pair of characters can turn it into a palindrome.
A swap chooses two distinct indices i and j (i != j) and exchanges s[i] and s[j]. Return True if exactly one swap can make the string a palindrome, and False otherwise. If s is already a palindrome, you still have to perform exactly one swap, and the string after the swap must also be a palindrome.
Function Signature
def can_be_palindrome_by_one_swap(s: str) -> bool:
Rules
-
Exactly one swap is performed, on two different indices. Swapping two equal characters is allowed and leaves the string unchanged.
-
A string of length 1 has no two distinct indices to swap, so the answer for it is
False
.
Constraints
-
1 <= len(s) <= 10^5
-
s
consists of lowercase English letters.
Examples
Input: s = "abcba"
Output: True
The string is already a palindrome. Swapping s[1] and s[3] (both 'b') keeps it a palindrome.
Input: s = "abcd"
Output: False
The mirrored pairs (a, d) and (b, c) both mismatch, and no single swap fixes both. Every letter also appears only once, so no arrangement of these four letters is a palindrome.
Input: s = "abab"
Output: True
Swapping s[0] and s[1] gives "baab", which is a palindrome.