Description: Given a string s, reverse the string according to the following rules:

  • All the characters that are not English letters remain in the same position.
  • All the English letters (lowercase or uppercase) should be reversed.
  • Return s after reversing it.

Code:

import string

def reverseOnlyLetters(self, s: str) -> str:
    letters = set(string.ascii_letters)
    result = list(s)
    left, right = 0, len(result) - 1

    while left < right:
        if result[left] not in letters:
            left += 1
        elif result[right] not in letters:
            right -= 1
        else:
            result[left], result[right] = result[right], result[left]
            left += 1
            right -= 1

    return ''.join(result)

Efficiency:

Time Complexity: O(n)

Space Complexity: O(n)

Test:

s = "ab-cd"
print(reverseOnlyLetters(s))#"dc-ba"

s = "a-bC-dEf-ghIj"
print(reverseOnlyLetters(s))#"j-Ih-gfE-dCba"

s = "Test1ng-Leet=code-Q!"
print(reverseOnlyLetters(s))#"Qedo1ct-eeLg=ntse-T!"