Problem
You are given a 0-indexed string s
consisting of only lowercase English letters. In one operation, you can change any character of s
to any other character.
Return true
if you can make s
a palindrome after performing exactly one or two operations, or return false
otherwise.
Examples
Example 1:
|
|
Solution
Method 1 - Using Two Pointer Technique
To determine if a string can be made into a palindrome with exactly one or two operations, we need to count the number of mismatches between the characters when the string is read from the beginning and the end. For a string to be transformed into a palindrome with one or two operations, the number of mismatches should be no more than 2.
Approach
- Use two pointers, one starting from the beginning (
left
) and the other from the end (right
) of the string. - Count the number of mismatches while traversing from both ends towards the center.
- If the number of mismatches is less than or equal to 2, return
true
; otherwise, returnfalse
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the string. - 🧺 Space complexity:
O(1)
for using a constant amount of space for the mismatch counter.