Move two pointers inward until both point at letters, swap them, and skip punctuation in place.
Complexity
O(n) time and O(n) space for the mutable character array.
Reverse only the letters in a string while leaving non-letter characters fixed.
Move two pointers inward until both point at letters, swap them, and skip punctuation in place.
O(n) time and O(n) space for the mutable character array.
package main
import "unicode"
func reverseOnlyLetters(s string) string {
characters := []rune(s)
left, right := 0, len(characters)-1
for left < right {
if !unicode.IsLetter(characters[left]) {
left++
} else if !unicode.IsLetter(characters[right]) {
right--
} else {
characters[left], characters[right] = characters[right], characters[left]
left++
right--
}
}
return string(characters)
}
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
characters = list(s)
left, right = 0, len(characters) - 1
while left < right:
if not characters[left].isalpha(): left += 1
elif not characters[right].isalpha(): right -= 1
else:
characters[left], characters[right] = characters[right], characters[left]
left, right = left + 1, right - 1
return "".join(characters)
function reverseOnlyLetters(s: string): string {
const characters = [...s];
const isLetter = (value: string): boolean => /[A-Za-z]/.test(value);
let left = 0;
let right = characters.length - 1;
while (left < right) { if (!isLetter(characters[left])) left += 1; else if (!isLetter(characters[right])) right -= 1; else { [characters[left], characters[right]] = [characters[right], characters[left]]; left += 1; right -= 1; } }
return characters.join("");
}