给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
示例 1:
输入:"ab-cd"
输出:"dc-ba"
示例 2:
输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"
示例 3:
输入:"Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"
提示:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S 中不包含 \ or "
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-only-letters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
res=[]
res=[i for i in S[::-1] if (i>='a' and i<='z') or (i>='A' and i<='Z')]
for i in range(len(S)):
if not ((S[i]>='a' and S[i]<='z') or (S[i]>='A' and S[i]<='Z')):
res.insert(i,S[i])
return ''.join(res)
执行结果:
通过
显示详情
执行用时 :28 ms, 在所有 Python 提交中击败了22.93%的用户
内存消耗 :12.7 MB, 在所有 Python 提交中击败了50.00%的用户