Given a string s
, reverse the string according to the following rules:
Return s
after reversing it.
For example:
s = "ab-cd"
should return "dc-ba"
s = "a-bC-dEf-ghIj"
should return "j-Ih-gfE-dCba"
s = "Test1ng-Leet=code-Q!"
should return "Qedo1ct-eeLg=ntse-T!"
Constraints:
1 <= s.length <= 100
s
consists of characters with ASCII values in the range [33, 122]
s
does not contain '\"'
or '\\'
.def reverseOnlyLetters(s: str) -> str:
letters = [c for c in s if c.isalpha()]
letters.reverse()
result = []
letter_index = 0
for c in s:
if c.isalpha():
result.append(letters[letter_index])
letter_index += 1
else:
result.append(c)
return "".join(result)
# Example Usage
s = "ab-cd"
print(reverseOnlyLetters(s)) # Output: dc-ba
s = "a-bC-dEf-ghIj"
print(reverseOnlyLetters(s)) # Output: j-Ih-gfE-dCba
s = "Test1ng-Leet=code-Q!"
print(reverseOnlyLetters(s)) # Output: Qedo1ct-eeLg=ntse-T!
s
.s
, and for each character:
s
. This is because we iterate through the string twice: once to extract the letters and once to rebuild the string.s
. This is because we store the extracted letters in a separate list, which can grow up to the size of the input string if all characters are letters.