难度: Easy
原题连接
内容描述
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \ or "
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
sb题没什么好说的
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
if not S or len(S) == 0:
return ''
tmp = []
res = []
for c in S:
if 'a' <= c <= 'z' or 'A' <= c <= 'Z':
tmp.append(c)
res.append(c)
tmp = tmp[::-1]
idx = 0
for i, c in enumerate(res):
if 'a' <= c <= 'z' or 'A' <= c <= 'Z':
res[i] = tmp[idx]
idx += 1
return ''.join(res)