Given a string s
, return the string after reversing the letters of s
without altering the positions of the non-letter characters.
Example 1:
Input: s = "ab-cd"
Output: "dc-ba"
Example 2:
Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Constraints:
1 <= s.length <= 100
s
consists of characters of the following types:
"
.”0
to 9
.left
) and the other from the end (right
) of the string.left
pointer until it finds a letter and decrement the right
pointer until it finds a letter.left
and right
pointers and then move the pointers toward the center.n
is the length of the string: Each character is processed at most once.def reverseOnlyLetters(s: str) -> str:
# Convert string to list for mutable operations
s_list = list(s)
left, right = 0, len(s) - 1
while left < right:
if not s_list[left].isalpha():
left += 1
elif not s_list[right].isalpha():
right -= 1
else:
# Swap the letters
s_list[left], s_list[right] = s_list[right], s_list[left]
left += 1
right -= 1
return ''.join(s_list)
# Example usage
print(reverseOnlyLetters("ab-cd")) # Output: "dc-ba"
print(reverseOnlyLetters("a-bC-dEf-ghIj")) # Output: "j-Ih-gfE-dCba"
print(reverseOnlyLetters("Test1ng-Leet=code-Q!")) # Output: "Qedo1ct-eeLg=ntse-T!"
In the above code:
left
and right
) to conditionally swap characters when they are both letters, otherwise, we adjust the pointers.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?