917. Reverse Only Letters(反转列表)
作者:互联网
题目
我的代码
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
i=0
j=len(S)-1
S=list(S)
while i<j:
if not S[i].isalpha():
i+=1
continue;
if not S[j].isalpha():
j-=1
continue
t=S[i]
S[i]=S[j]
S[j]=t
i+=1
j-=1
return ''.join(S)
优秀代码
其中间,用了while效率更高一些。
class Solution(object):
def reverseOnlyLetters(self, S):
"""
:type S: str
:rtype: str
"""
s = []
i = 0
j = len(S) -1
for i, x in enumerate(S):
if x.isalpha():
while not S[j].isalpha():
#i +=1
j-=1
s.append(S[j])
j -=1
else:
s.append(x)
return "".join(s)
标签:Letters,Reverse,self,while,Only,isalpha,str,type,append 来源: https://blog.csdn.net/xiabenshu/article/details/88993129